Skip to content Skip to sidebar Skip to footer

Regex Sub Phone Number Format Multiple Times On Same String

I'm trying to use reg expressions to modify the format of phone numbers in a list. Here is a sample list: ['(123)456-7890 (321)-654-0987', '(111) 111-1111', '222-222-2222', '(333)3

Solution 1:

Here's a more simple solution that works for all of those cases, though is a little naïve (and doesn't care about matching brackets).

\(?(\d{3})\)?[ -.]?(\d{3})[ -.]?(\d{4})

Replace with:

(\1)\2-\3

Try it online

Explanation:

Works by first checking for 3 digits, and optionally surrounding brackets on either side, with \(?(\d{3})\)?. Notice that the 3 digits are in a capturing group.

Next, it checks for an optional separator character, and then another 3 digits, also stored in a capturing group: [ -.]?(\d{3}).

And lastly, it does the previous step again - but with 4 digits instead of 3: [ -.]?(\d{4})

Python:

To use it in Python, you should just be able to iterate over each element in the list and do:

p.sub('(\\1)\\2-\\3', myString) # Note the double backslashes, or...
p.sub(r'(\1)\2-\3', myString)   # Raw strings work too

Example Python code


EDIT

This solution is a bit more complex, and ensures that if there is a close bracket, there must be a start bracket.

(\()?((?(1)\d{3}(?=\))|\d{3}(?!\))))\)?[ -.]?(\d{3})[ -.]?(\d{4})

Replace with:

(\2)\3-\4

Try it online

Post a Comment for "Regex Sub Phone Number Format Multiple Times On Same String"