C# Regular Expression: {4} and more then 4 values possible
I'm in need of a regular expression that checks if the input is exactly 4 numbers. I'm using "\d{4}" (also tried "\d\d\d\d"). But if you enter 5 numbers, it also says the input is valid.
[TestMethod]
public void RegexTest()
{
Regex expr = new Regex("\\d{4}");
String a = "4444", b = "4l44", c = "55555", d = "5 55";
Match mc = expr.Match(a);
Assert.IsTrue(mc.Success);
mc = expr.Match(b);
Assert.IsFalse(mc.Success);
***mc = expr.Match(c);
Assert.IsFalse(mc.Success)***;
mc = expr.Match(d);
Assert.IsFalse(mc.Success);
}
(it's the c that is 'true' but 开发者_Python百科should be false, the others work)
Thanks in advance, ~Sir Troll
If it must be exactly 4, then you need to use $ and ^ to mark end and start of the input:
Regex expr = new Regex(@"^\d{4}$");
Note I'm also using verbatim string literals here, so save on sanity - then you don't need to C#-escape all your regex-escape-characters. Only "
needs escaping in the C# (to ""
).
"55555" contains "5555", which is valid... So the string contains a match, even though the match isn't the complete string. See Marc's answer for the solution
a string with 5 digits also contains 4 digits, so you have to make sure that you also add start and end of string contraints.
This should work as your Regex:
Regex expr = new Regex(@"^\d{4}$");
精彩评论