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 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 "").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With