Regular Expression Phone Number and Phone Extension

I have a regex that clears phone numbers and turns them into valid phone numbers as such: +1 123-1223.

Regular expression:

Regex.Replace(phone, @"^\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*$", "+1 $1$2$3-$4$5$6-$7$8$9$10");

But I would like to add to it that all over 12 numbers add the remaining numbers as an extension. So, if the number is 810.232.122323, it will become +1 810-232-1223 x23.

Is this possible by changing the regex? Is there a good way to do this? I do not know regular expressions. Thank!

+3
source share
1 answer

Just add this to the end, it will be your 11th group (and it won’t get the extension if it really doesn’t have 2 digits or more

(\d{2,})

The code will be:

Regex.Replace(phone, 
    @"^\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d{2,})$", 
    "+1 $1$2$3-$4$5$6-$7$8$9$10 Ext $11");

If this is not necessary, do the following:

(\d{2,})?

- , , ,

, Ext, MatchEvaluator

- ( , )

Regex.Replace(phone, 
    @"^\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d{2,})$", 
    "+1 $1$2$3-$4$5$6-$7$8$9$10 Ext $11");
     match =>
     {
         var returnVal = "+1 ";
         for(int i = 1; i <= 3; i++)
         {
             returnVal += match.Groups[i].Value;
             if(i == 3 || i == 6)
                 returnVal += "-";
         }
         returnVal += match.Groups[11].Success ? " Ext " + match.Groups[11] : "" )
         return returnVal;
     }
)
+2

All Articles