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
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.