Rhs
Rhs

Reputation: 3318

Regular Expression \d matches with multiple numbers

I was looking at a C# Regex tutorial which stated that "\d" matches a single digit 0 to 9.

However when I ran the following program.

    static void Main(string[] args)
    {
        string s = "45";
        Regex myRegex = new Regex(@"(\d)");

        if( myRegex.IsMatch(s))
        {
            System.Console.WriteLine("Matched");
        }
        else
        {
            System.Console.WriteLine("Not Matched");
        }

        Console.ReadKey();
    }

The console printed out "Matched".

Upvotes: 1

Views: 1262

Answers (2)

MoX
MoX

Reputation: 93

Regex myRegex = new Regex(@"^\d$");

Upvotes: 3

Martin Ender
Martin Ender

Reputation: 44259

Well yeah, it finds the 4, because regular expression matches do not have to cover the full input string. If you want to make sure that your string is only a single digit, include anchors, that mark the beginning and end of the string:

Regex myRegex = new Regex(@"^(\d)$");

Now the match has to start at the beginning of the string (marked by ^) and has to end at the end of the string (marked by $). Thus, only single-digit inputs will be allowed. Omitting this allows the regular expression to match any substring of your input.

Upvotes: 10

Related Questions