开发者

C# .NET Regex problem

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 o开发者_JAVA百科f 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!


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜