Regex fails to match string

2019-08-23 12:04发布

问题:

I have a piece of code below which I am trying to use to match the start and the end of a string where the middle can change. I am first trying to get this example working could someone please tell me the error with this code and why it is not matching at all.

      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:

You don't need the delimiters, in c# you just specify the Regex:

  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:

If only the middle portion of the string in question is subject to change, then why not use String.StartsWith and String.EndsWith? For example:

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

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