Reputation: 7717
Similar to my question from yesterday: C# Regex Pattern Conundrum
Same issue, different regex pattern. The regex pattern returns the desired match when tested in http://sourceforge.net/projects/regextester/ and http://www.RegexLib.com But, when the pattern is executed in .NET there are no matches returned.
string SampleText = @"\r\n99. Sample text paragraph one.\r\n100. Sample text here paragraph two.\r\n101. Sample text paragraph three.\r\n";
string RegexPattern = @"(?<=\\r\\n\d+\.\s)([^.]+?)here.*?(?=\\r\\n)";
Regex FindRegex = new Regex(@RegexPattern, RegexOptions.Multiline | RegexOptions.Singleline);
Match m = FindRegex.Match(SampleText);
The desired match is "Sample text here paragraph two."
As with yesterday, I'm not sure, if the issue is my regex pattern or my code.
Upvotes: 1
Views: 450
Reputation: 7717
I figured it out.
When testing in RegexTester and RegexLib.com I copy and pasted my source text from the Immediate Window which converted control return line feeds to their text representation \r\n.
So, my regex worked in the test environment. But, in actual runtime, the source text contained control return line feed, not \r\n as text. Which explains why my pattern worked in the test environment, but not at runtime.
I changed my pattern to @"(?<=\n\d+\.\s)([^.]+?)here.*?(?=\n)"
and it worked beautifully.
Embarrassing realization. Thanks for your help Oded.
Upvotes: 0
Reputation: 499352
You need to escape the special regex characters too:
string RegexPattern = @"(?<=\\r\\n\d+\.\s)([^.]+?)here.*?(?=\\r\\n)";
Or:
string RegexPattern = "(?<=\\\\r\\\\n\\d+\\.\\s)([^.]+?)here.*?(?=\\\\r\\\\n)";
Don't forget - you are in a C# string context, so you need to ensure that you pass in the correct string to the regex engine.
Upvotes: 7