Home > Software engineering >  Validate insert 1 or not depending of phone value regex
Validate insert 1 or not depending of phone value regex

Time:05-28

I have a regular expression, so I want to add 1 when number does not start with it. And if it starts with 1 it should display as 1 then (###)-###-####

But it is throwing 1 1-(###)-###-#### when the number starts with 1

Expression:

 var formattedShipperPhone = Regex.Replace(model.Shipper.ContactPhone, @"(?:\ 1[\- /]?)?([2-9]\d{2})[\- /]?([2-9]\d{2})[\- /]?(\d{4})", " 1-($1)-$2-$3");

How can I validate the 1 if it already has it or not?

CodePudding user response:

It is because you are matching 1 and if there is no plus sign you will also not match the 1 so it is untouched and stays in the replacement.

The can be optional, and you don't have to escape the \-

Example

var strings = new List<string>() {
    " 1-288-388-4441",
    " 1288-388-4442",
    "1288-388-4443",
    "288-388-4444",
};
            
foreach (var s in strings)
{
    Console.WriteLine(
        Regex.Replace(
            s, 
            @"(?:\ ?1[- /]?)?([2-9]\d{2})[- /]?([2-9]\d{2})[- /]?(\d{4})", 
            " 1-($1)-$2-$3")
        );
}

Output

 1-(288)-388-4441
 1-(288)-388-4442
 1-(288)-388-4443
 1-(288)-388-4444

CodePudding user response:

I don't like use .* in regex, but in this example you can try

".*([2-9]\d{2})[\- /]?([2-9]\d{2})[\- /]?(\d{4})"

and get

" 1-($1)-$2-$3"

In this case you will always delete what is before (###)-###-#### and just add 1

  • Related