Skip to content

Instantly share code, notes, and snippets.

@Codehunter-py
Last active August 23, 2023 11:55
Show Gist options
  • Save Codehunter-py/e138c804067fab7f9740e6507891dc4e to your computer and use it in GitHub Desktop.
Save Codehunter-py/e138c804067fab7f9740e6507891dc4e to your computer and use it in GitHub Desktop.
The convert_phone_number function checks for a U.S. phone number format: XXX-XXX-XXXX (3 digits followed by a dash, 3 more digits followed by a dash, and 4 digits), and converts it to a more formal format that looks like this: (XXX) XXX-XXXX.
import re
def convert_phone_number(phone):
result = re.sub(r"\b(\d{3})-(\d{3})-(\d{4})\b",r"(\1) \2-\3", phone)
return result
print(convert_phone_number("My number is 212-345-9999.")) # My number is (212) 345-9999.
print(convert_phone_number("Please call 888-555-1234")) # Please call (888) 555-1234
print(convert_phone_number("123-123-12345")) # 123-123-12345
print(convert_phone_number("Phone number of Buckingham Palace is +44 303 123 7300")) # Phone number of Buckingham Palace is +44 303 123 7300
Copy link

ghost commented Jul 21, 2022

if i remove both \b it also includes 3rd one but why is that, even if i specified 3rd group's length is 4

@Codehunter-py
Copy link
Author

Hi,

\b
Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.

Resource: https://docs.python.org/3/library/re.html#:~:text=Inside%20a%20character%20range%2C%20%5Cb,compatibility%20with%20Python's%20string%20literals.&text=Matches%20the%20empty%20string%2C%20but,or%20end%20of%20a%20word.

@4gungnand
Copy link

Hi,

\b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.

Resource: https://docs.python.org/3/library/re.html#:~:text=Inside%20a%20character%20range%2C%20%5Cb,compatibility%20with%20Python's%20string%20literals.&text=Matches%20the%20empty%20string%2C%20but,or%20end%20of%20a%20word.

thank you for both the code 👍 and clear explanation ~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment