【问题标题】:My Azure regex not working as expected [duplicate]我的 Azure 正则表达式未按预期工作 [重复]
【发布时间】:2018-07-01 18:05:25
【问题描述】:

我正在尝试下面的代码来查找有效和无效的名称

string pattern = @"((?:[GE\-[RGrp]+))";
            foreach (var AzureResponse in Response)
            {

                if (AzureResponse.name!= null)
                {
                    Console.WriteLine("{0},{1} a valid resource name.", AzureResponse.name, Regex.IsMatch(@AzureResponse.name, pattern) ? "is" : "Is not");


                }

            }

但它打印出所有资源名称都是有效的,即使我知道很少有,似乎我无法获得正确的正则表达式。

我想要的是:

  • 任何以"GE-RGrp"开始的名称都应该是有效的,其余的都是无效的

【问题讨论】:

  • 根据您提供的描述,测试 .StartsWith("GE-RGrp-") 不是更好吗?
  • 这个[GE\-[RGrp]是一个字符类G,E,-,[,R,G,r,@9876543与+。因此,任何带有这些字母/符号的字符组都将被匹配。如果走正则表达式路线,最好使用 \bGE-RGrp(\w+)\b(GE-RGrp\w+)
  • 试试@AzureResponse.name.StartsWith("GE-RGrp")。如果您检查字符串是否以文字子字符串开头,则无需使用正则表达式。

标签: c# regex validation


【解决方案1】:

如果您打算使用正则表达式,那么string pattern = @"^GE-RGrp"; 应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2014-04-28
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多