5

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.

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Tried that already. Regex.Match(SampleText, @RegexPattern, RegexOptions.Multiline).Groups[1].Value.ToString() returns an empty string
what if you include the RegexOptions.Multiline | RegexOptions.Singleline as well
Thanks Miky! It needed both Multiline and Singleline.
0

You don't need RegexOptions.Multiline.

The problem in your case is that the dot matches any character except line break characters (\r\ and \n).

So, you'll need to define your regex pattern like so: (?<=starttexthere)[\w\r\n]+(?=endtexthere) in order to specifically match text across line breaks.

Here's an online running sample: http://ideone.com/ZXgKar

1 Comment

@s15199d yes, it does match. Also, the code in the ideone link works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.