Home > Mobile >  Regex & Phone Numbers
Regex & Phone Numbers

Time:05-24

So I have been working on creating a regex to validate phone numbers in the following format XXX-XXX-XXXX which has been working pretty well so far, but now I'm trying to figure out how to remove the ability to enter specific numbers like "123-456-7890".

My current regex is

(^[0-9]{3}-[0-9]{3}-[0-9]{4}$)

I've been looking into it for a few days, but I can't seem to figure out what to add to my current expression in order to get "any number with formats XXX-XXX-XXXX BUT NOT 123-456-7890"

Can anyone help me with this?

Thank you so much

CodePudding user response:

If negative look-ahead is supported in whatever version you're running, this should work:

(^(?!123-456-7890)[0-9]{3}-[0-9]{3}-[0-9]{4}$)

It's the same expression you used, just with a negative look-ahead added in the beginning.
(?!123-456-7890) checks if the character sequence ahead doesn't match the pattern '123-456-7890'.
Only if this condition is met, the rest of the pattern will be considered.

The same can be done by checking after matching the pattern using the look-behind expression (?<!123-456-7890)

(^[0-9]{3}-[0-9]{3}-[0-9]{4}(?<!123-456-7890)$)

in case that's faster or more practical for you.

https://regex101.com/r/GOyOgf/1

CodePudding user response:

I would break them into 2 regexes for simplicity and you can use an alternation for the not matches, like this:

        var regexToMatch = new Regex("(^[0-9]{3}-[0-9]{3}-[0-9]{4}$)");
        var regexToNotMatch = new Regex("(123-456-7890)|(098-765-4321)");
        
        var testString = "123-456-7890";
        
        if(regexToMatch.IsMatch(testString) && !regexToNotMatch.IsMatch(testString))
        {
            Console.WriteLine("Valid!");    
        }
        else
        {
            Console.WriteLine("Not Valid!");
        }

And here's a working fiddle of it.

  • Related