1

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.

0

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

There's actually a "\r\n" in the source string. Not a control return line feed, but the actual text. That, and I edited the op, to better represent my actual code by making the sample text and pattern literals.
@s15199d - Answer updated. \ is an escape sequence for both regular expressions and C# string literals, so you need to "double escape" them.
0

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.

Comments

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.