0

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);
Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
user101010101
  • 1,609
  • 6
  • 31
  • 52
  • 2
    What are you trying to capture? I'm not sure I get it from your regex supplied. Also, the obligatory [don't parse xml/html with regex](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Brad Christie Mar 02 '11 at 14:33
  • Please don't start a new question immediately, I already answered your question in your original question. – markijbema Mar 02 '11 at 14:38

2 Answers2

3

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);
TimCodes.NET
  • 4,601
  • 1
  • 25
  • 36
1

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...
}
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • The regex does not use ^ and $, therefore it does not need to match the whole string, and the match need not be at the start and end of the string. – markijbema Mar 02 '11 at 14:37
  • Maybe I'm dumb, but I read `'... trying to use to match the start and the end of a string where the middle can change'`. – Grant Thomas Mar 02 '11 at 14:39