Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex Pattern Conundrum

Tags:

c#

regex

I have a regex that I've verified in 3 separate sources as successfully matching the desired text.

  1. http://regexlib.com/RETester.aspx
  2. http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx,
  3. http://sourceforge.net/projects/regextester/

But, when I use the regex in my code. It does not produce a match. I have used other regex with this code and they have resulted in the desired matches. I'm at a loss...

string SampleText = "starttexthere\r\nothertexthereendtexthere";
string RegexPattern = "(?<=starttexthere)(.*?)(?=endtexthere)";
Regex FindRegex = new Regex(@RegexPattern);
Match m = FindRegex.Match(SampleText);

I don't know if the problem is my regex, or my code.

like image 395
s15199d Avatar asked Mar 07 '13 15:03

s15199d


1 Answers

The problem is that your text contains a \r\n which means it is split across two lines. If you want to match the whole string you have to set the option to match across multiple lines, and to change the behavior of the . to include the \n (new-line character) in matched

 Regex FindRegex = new Regex(@RegexPattern, RegexOptions.Multiline | RegexOptions.Singleline);
like image 154
Mike Dinescu Avatar answered Oct 08 '22 07:10

Mike Dinescu