【问题标题】:How to extract the first 3 free standing characters from a string?如何从字符串中提取前 3 个独立字符?
【发布时间】:2021-09-19 16:28:13
【问题描述】:

我有一个程序需要解析城镇名称。有时用户输入了正确的城镇名称,但用户通常输入邮政编码作为城镇名称。

如果我无法将城镇名称与有效城镇名称匹配,我假设输入包含邮政编码。邮政编码的前 3 个独立字符可唯一标识城镇。

邮政编码的格式为 3 个字母后跟 3 个数字,例如ABC123.

但是有些用户在字母前输入数字,有些用户将城镇名称和邮政编码结合起来,例如

123ABC
Pretty city ABC123

如何提取前 3 个独立字符?

独立=左右3个字符没有其他字符。

对于以下字符串,ABC 是前 3 个独立字符。

ABC123
123ABC
ABC 123
123 ABC
123 ABC 456
ABC12DEF
123 ABC DEF
DE 123 ABC
Pretty city ABC123

这些下一个字符串没有 3 个独立字符。

123ABCDEF
ABCD123
123ABCD
123 ABCD
Somename1234
1234Somename

大小写无关。

这是我的尝试

使用正则表达式。不适用于“美丽城市 ABC123”

    Regex rgx = new Regex("[a-zA-Z]{3}");
    string hamster = "ABC123";
    var code = rgx.Match(hamster);

尴尬的功能

private static string GetCode(string pig)
{
  var code = "";
  var canstart = true;
  for (int i = 0; i < pig.Length; i++)
  {
    //Console.WriteLine(code);
    if (code.Length == 3)
    {
      if (char.IsLetter(pig[i]))
      {
        canstart = false;
        code = "";
      }
      else
      {
        break;
      }
    }
    if (char.IsLetter(pig[i]) && canstart)
    {
      code += pig[i];
    }
    else if (!char.IsLetter(pig[i]) && !canstart)
    {
      canstart = true;
    }
  }

  if (code.Length != 3)
  {
    code = "";
  }
  return code;
}

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    你可以使用

    (?<![a-zA-Z])[a-zA-Z]{3}(?![a-zA-Z])
    

    请参阅regex demo详情

    • (?&lt;![a-zA-Z]) - 一个否定的向后查找,匹配一个没有紧跟在 ASCII 字母前面的位置
    • [a-zA-Z]{3} - 三个 ASCII 字母
    • (?![a-zA-Z]) - 与未紧跟 ASCII 字母的位置匹配的负前瞻。

    在 C# 中:

    var rgx = new Regex(@"(?<![a-zA-Z])[a-zA-Z]{3}(?![a-zA-Z])");
    var hamster = "ABC123";
    var code = rgx.Match(hamster)?.Value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 2019-01-07
      • 2022-06-21
      • 2016-11-05
      • 2012-03-03
      • 1970-01-01
      • 2016-12-23
      相关资源
      最近更新 更多