开发者

c# regex and [] expression , why does [+*/-] fail to parse?

i tried to use Regex in c# , but the following code throws an exception:

string pattern = "(\d+)([+*/-])(\d+)";

Regex reg = new Regex  (pattern);

After a little dig , i fou开发者_C百科nd that in c# if you try to match '-' with [] expression , it must be put as the first character in that bracket , which confused me.

Could someone jump out and explain that to me ?

Appreciate any of your responses.


The - character takes on a special meaning within a character class [...] to denote a range, so that shorthand expressions like the following work:

"[a-z]" // matches all lowercase alphabetic characters without having to specify them all.

The - is only interpreted literally if it is the first character simply because it can't denote a range because no other value precedes it.

Honestly, it should make no difference whether it is the first or the last character.


That code doesn't throw a runtime exception - that code doesn't compile, with the error "Unrecognized escape sequence" - you didn't escape the backslashes properly. \d isn't a valid escape character.

This should work:

string pattern = "(\\d+)([+*/-])(\\d+)";

Or this, using verbatim string literals:

string pattern = @"(\d+)([+*/-])(\d+)";
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜