'How to convert 10 digits with this format XXX-XXX-XXXX to US formal format that looks like (XXX) XXX-XXXX using Python3 Regex sub
This is my try, it actually put the first and seconds groups of 3 digits between parenthesis while I only need to put the first group only between parenthesis to meet US phone number formal format like (XXX) XXX-XXXX. I am asked to do this using re.sub only which means it is a pattern matter and correct syntax which I am missing actually. Thank you very much.
import re
def convert_phone_number(phone):
result = re.sub(r"(\d+-)", r"(\1)", phone) # my actual pattern - change only this line
return result
print(convert_phone_number("My number is 212-345-9999.")) # output should be: My number is (212) 345-9999.
# my actual output: My number is (212-)(345-)9999.
print(convert_phone_number("Please call 888-555-1234")) # output should be: Please call (888) 555-1234
# my actual output: Please call (888-)(555-)1234
Solution 1:[1]
You may use
re.sub(r'(?<!\S)(\d{3})-', r'(\1) ', phone)
See regex demo
Details
(?<!\S)
- a left-hand whitespace boundary(\d{3})
- Capturing group #1: three digits-
- a hyphen.
The replacement is the Group 1 value inside round brackets and a space after (that will replace the hyphen).
Solution 2:[2]
This result will include the checking part for phone format (it must be XXX-XXX-XXXX), if it correct the re.sub function will pass:
import re
def convert_phone_number(phone):
result = re.sub(r'(?<!\S)(\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
Solution 3:[3]
re.sub(r"\b\s(\d{3})-", r" (\1) ", phone)
Solution 4:[4]
import re
def convert_phone_number(phone):
result = re.sub(r"\b\s(\d{3})-\b", r" (\1) ", phone)
return result
Solution 5:[5]
import re
def convert_phone_number(phone):
result = re.sub(r" (\d{3})-",r" (\1) ",phone)
return result
Solution 6:[6]
Use This:
result = re.sub(r"(\b\d[0-9]{2}\b)-(\b[0-9]{3}\b-\b[0-9]{4}\b)", r"(\1) \2", phone)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wiktor Stribiżew |
Solution 2 | Hi?u H? |
Solution 3 | RavinderSingh13 |
Solution 4 | waithira |
Solution 5 | Muhammad Umar Asad |
Solution 6 | Nick |