Saturday, January 18, 2025
HomeProgrammingWhat regular expression can be used to reformat a US phone number?

What regular expression can be used to reformat a US phone number?

To reformat a US phone number using a regular expression, you can use the re.sub() method in Python. For example, to convert various formats into (XXX) XXX-XXXX, use:

import re

phone = “123-456-7890″
formatted_phone = re.sub(r”\D”, “”, phone) # Remove non-digit characters
formatted_phone = re.sub(r”(\d{3})(\d{3})(\d{4})”, r”(\1) \2-\3″, formatted_phone)
print(formatted_phone) # Outputs: (123) 456-7890

See also  How do I use OpenSSL to Retrieve a Certificate from a Server?

This approach ensures consistency by stripping unwanted characters and applying the desired format. Modify the pattern as needed for other formats. Ensure input validation to handle edge cases effectively.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x