简体   繁体   中英

Regex fails to match string

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);

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);

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM