如何使用Python3 Regex sub将格式为XXX-XXX-XXXX的10位数字转换为类似(XXX)XXX-XXXX的美国正式格式

hi3rlvi2  于 2023-01-03  发布在  Python
关注(0)|答案(9)|浏览(203)

这是我的尝试,它实际上把第一和第二组3位数字之间的括号,而我只需要把第一组之间的括号,以满足美国电话号码的正式格式,如(XXX)XXX-XXXX。我被要求这样做使用re.sub只这意味着它是一个模式的问题和正确的语法,我错过了实际上。非常感谢。

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
ovfsdjhp

ovfsdjhp1#

您可以使用

re.sub(r'(?<!\S)(\d{3})-', r'(\1) ', phone)

参见regex demo

    • 详细信息**
  • (?<!\S)-左侧空白边界
  • (\d{3})-捕获组#1:三位数
  • --连字符。

替换为圆括号内的Group 1值和后面的空格(将替换连字符)。

m2xkgtsf

m2xkgtsf2#

此结果将包括电话格式的检查部分(必须为XXX-XXX-XXXX),如果正确,则re.sub函数将通过:

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
jyztefdp

jyztefdp3#

re.sub(r"\b\s(\d{3})-", r" (\1) ", phone)
tcomlyy6

tcomlyy64#

import re
def convert_phone_number(phone):
  result = re.sub(r"\b\s(\d{3})-\b", r" (\1) ", phone)
  return result
wvyml7n5

wvyml7n55#

import re
def convert_phone_number(phone):
  result = re.sub(r" (\d{3})-",r" (\1) ",phone)
  return result
dz6r00yl

dz6r00yl6#

使用此:

result = re.sub(r"(\b\d[0-9]{2}\b)-(\b[0-9]{3}\b-\b[0-9]{4}\b)", r"(\1) \2", phone)
0x6upsns

0x6upsns7#

result = re.sub(r"(\d{3})-(\d{3})-(\d{4}\b)", r"(\1) \2-\3" , phone)
r1zhe5dt

r1zhe5dt9#

import re
def convert_phone_number(phone):
  result = re.sub(r'(.+)(\d{3})-(\d{3}-\d{4})',r'\1(\2) \3',phone)
  return result
''' the regex searches for  any character with more than 1 occurrence,before the phone format, then the replacement regex formats the string'''
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

相关问题