1

I am trying to find out a solution to an issue I'm having. If I execute the following C# code:

Regex r = new Regex("[\\r\\n]*");
Match m = r.Match("\\r\\n");

If I examine the value of m.Success, I get a value of true, which is correct. But if I examine the value of m.Length, I get a value of 0. If I examine m.Value, I also get a blank value. Am I missing something in my Regex? I am under the impression that either m.Success needs to be false and m.Length is 0 or else m.Success needs to be true and m.Length needs to be greater then 0. Any help on clearifing this would be appreciated!

2
  • shouldn't the second line be Match m = r.Match("\r\n"); ? I imagine this is a string with actual cr/lf chars, not escaped ? Commented Jul 6, 2011 at 4:54
  • if you leave out one '\', it does do the job... But I do not know if that is what is intended... Commented Jul 6, 2011 at 4:56

1 Answer 1

6

Match.Success returns true because the Regex is supposed to match "zero or more" instances of "\r" or "\n", that is, carriage return or line feed, (as indicated by the "*" symbol). However, the string you gave (within Match) instead contains backslash, r, backslash, n, which is neither a carriage return nor a line feed, so the length of the match was zero. (Within the regular expression, the "backslash, n" is treated as a single character, line feed).

To avoid further confusion in the future, try prefixing the regular expression with an "@" symbol to possibly avoid some confusion with how the backslashes work in regular expressions, like this:

 @"[\r\n]*"

Hopefully this makes it a little clearer that "\r" stands for a carriage return and "\n" for a line feed. The related regular expression:

 @"[\\rn]*"

Would match zero or more instances of backslashes, r, and/or n. (The doubled backslash is necessary because that symbol is treated specially in regular expressions.)

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

1 Comment

Such a frickin' obvious mistake on my part. Thanks Peter

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.