0

In c# I have a regex and I can't get my head around why it is not matching.

The pattern (abc\r\n)* should match the abc\r\nabc\r\n in the string 123\r\nabc\r\nabc\r\n345

Regex regex = new Regex("(abc\r\n)*", RegexOptions.Compiled);

var mat = regex.Match("123\r\nabc\r\nabc\r\n345");

The funny thing is that mat.Success returns true. enter image description here

The same pattern matches online

1 Answer 1

1

The Match method works as expected. Actually the pattern (abc\r\n)* will find 12 matches. The Match method returns to you the first match only which is an empty string. So that if you are looking to match abc\r\nabc\r\n exactly you should use this pattern:

Regex regex = new Regex("(abc\r\nabc\r\n)", RegexOptions.Compiled);

if you like to match all abc\r\n you should use:

Regex regex = new Regex("(abc\r\n)", RegexOptions.Compiled);

var mat = regex.Matches("123\r\nabc\r\nabc\r\n345");

And so on, bottom line is that the problem is in the pattern itself.

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

3 Comments

Can you elaborate why the first 12 matches are empty?
Also, I thought that regex is greedy, and should go on to match the longest possible sequence of chars. Why is that not happening.
The "*" notation matches zero or more occurrences of the regular expression so that you get the empty strings as matches. users.cs.cf.ac.uk/Dave.Marshall/Internet/NEWS/regexp.html

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.