正则表达式无法匹配字符串

时间:2011-03-02 14:30:18

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

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

      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 个答案:

答案 0 :(得分:3)

您不需要分隔符,在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);

答案 1 :(得分:1)

如果只有相关字符串的中间部分可能会发生变化,那么为什么不使用String.StartsWithString.EndsWith?例如:

var myStringPrefix = "prefix";
var myStringSuffix = "suffix";
var myStringTheChangeling = "prefix random suffix";

if (myStringTheChangeling.StartsWith(myStringPrexix) &&
    myStringTheChangeling.EndsWith(myStringSuffix))
{
    //good to go...
}
相关问题