Regex returns true even the input does not match the pattern

I'm using System.Text.RegularExpressions to validate input but my regex still returns true.

string regex = @"([+]93|0)([0-9]{10})";
Regex rx = new Regex(regex,RegexOptions.Compiled | RegexOptions.IgnoreCase);
////tests 
Console.WriteLine(Regex.IsMatch("01234567890", regex)); //expected: true
Console.WriteLine(Regex.IsMatch("+931234567890", regex)); //expected: true
Console.WriteLine(Regex.IsMatch("+931234567890A", regex)); //expected: false
Console.WriteLine(Regex.IsMatch("A+931234567890", regex)); //expected: false

but all the tests cases returns true. How can I make it only return true if the input exactly match the pattern and the supposed length of the pattern?

2 answers

  • answered 2019-08-13 03:24 John

    The reason they match is that you haven't included any requirement to match the whole string, for example.

    You can use the following operators to help you:

    • ^ matches the start of the string.
    • $ matches the end of the string.

    So you could change your regex to match the entire string, such that it can only be the phone number:

    ^([+]93|0)([0-9]{10})$
    

    Try it online

  • answered 2019-08-13 03:27 Isaac McClure

    You need to use the ^ to indicate the start of the string to match, and $ to indicate the end of the string to match.

    The regex you're looking for is "^([+]93|0)([0-9]{10})$".