如何使用 Python3 Regex 子将具有此格式 XXX-XXX-XXXX 的 10 位数字转换为看起来像 (XXX) XXX-XXXX 的美国正式格式

新手上路,请多包涵

这是我的尝试,它实际上将第一组和第二组的 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

原文由 user13824946 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

你可以使用

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

查看 正则表达式演示

细节

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

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

原文由 Wiktor Stribiżew 发布,翻译遵循 CC BY-SA 4.0 许可协议

此结果将包括电话格式的检查部分(必须是 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

原文由 Hiếu Hồ 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Stack Overflow 翻译
子站问答
访问
宣传栏