【问题标题】:Regex fails to match string正则表达式无法匹配字符串
【发布时间】:2023-03-18 20:09:01
【问题描述】:

我在下面有一段代码,我试图用它来匹配中间可以更改的字符串的开头和结尾。我首先尝试让这个示例正常工作,有人可以告诉我此代码的错误以及为什么它根本不匹配。

      string pattern = @"/\/>[^<]*abc/";
      string text = @"<foo/> hello first abc hello second abc <bar/> hello third abc";
      Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
      Match m = r.Match(text);

【问题讨论】:

  • 你想捕捉什么?我不确定我是否从您提供的正则表达式中得到它。另外,必填don't parse xml/html with regex
  • 请不要立即开始新问题,我已经在您原来的问题中回答了您的问题。

标签: c# regex pattern-matching string-matching


【解决方案1】:

您不需要分隔符,在 c# 中您只需指定正则表达式:

  string pattern = @"\/>[^<]*abc";


  string text = @"<foo/> hello first abc hello second abc <bar/> hello third abc";


  Regex r = new Regex(pattern, RegexOptions.IgnoreCase);


  Match m = r.Match(text);

【讨论】:

    【解决方案2】:

    如果只有问题字符串的中间部分可以更改,那么为什么不使用String.StartsWithString.EndsWith?例如:

    var myStringPrefix = "prefix";
    var myStringSuffix = "suffix";
    var myStringTheChangeling = "prefix random suffix";
    
    if (myStringTheChangeling.StartsWith(myStringPrexix) &&
        myStringTheChangeling.EndsWith(myStringSuffix))
    {
        //good to go...
    }
    

    【讨论】:

    • 正则表达式不使用^和$,因此不需要匹配整个字符串,也不需要匹配在字符串的开头和结尾。
    • 也许我很笨,但我读过'... trying to use to match the start and the end of a string where the middle can change'
    猜你喜欢
    • 2012-06-05
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多