开发者

RegEx prob with a range in a bracket

I have just studied the RegEx and I find myself confusing from this following counter example

Regex pattern = new Regex("[^1]{1,}");
string challenge = "1234";
Console.WriteLine(pattern.IsMatch(challenge));

It returns "True" on the console. From my understanding, it should give a "False" result because of having a '1' inside the challenge string. While this code works fine

Regex pattern = new Regex("[^1-5]{1,}");
string challenge = "1234";
Console.WriteLine(pattern.IsMatch(challenge));

The result is "False" as expected.

Does anyone have an idea开发者_Go百科 what is going on with the first code?


You are not anchoring the regex. Therefore, it is allowed to match any substring of the challenge string. (The substring "234" is matching the expression.) Try this:

Regex pattern = new Regex("^[^1]{1,}$");

The second regex fails to match the string, because no substring of the challenge string meets the expression "at least one character, except the characters 1, 2, 3, 4, and 5."

In short: If you want the regex to match the whole string, always remember to anchor the expression.


[^1]{1,} just means match any sequence of characters that does not contain 1 and has a length of at least 1.

1234 contains the sequence 234 which does not contain 1 and has length 3.


you don't mention the language, I guess it's C#? if isMatch() is equivalent to python's pattern.search(string), then it matches on "234" all of which are "not 1".


The string part "234" does match the regex. It's a string consisting of 1 or more occurences of not 1.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜