Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regular Expression: {4} and more then 4 values possible

Tags:

c#

regex

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

like image 966
Sir Troll Avatar asked Jan 20 '23 15:01

Sir Troll


1 Answers

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

like image 180
Marc Gravell Avatar answered Jan 25 '23 23:01

Marc Gravell