【问题标题】:Appending a +1 to string of digits with re.sub使用 re.sub 将 +1 附加到数字字符串
【发布时间】:2020-04-22 14:13:20
【问题描述】:

如何使用 re.sub python 方法将 +1 附加到电话号码?

当我使用以下函数时,它会将字符串“802-867-5309”更改为字符串“+1+15309”。我正在尝试获取此字符串“+1-802-867-5309”。文档替换中的示例显示了如何替换整个字符串我不想替换整个字符串只需附加一个 +1

import re
def transform_record(record):
  new_record = re.sub("[0-9]+-","+1", record)
  return new_record

print(transform_record("Some sample text 802-867-5309 some more sample text here"))

【问题讨论】:

    标签: regex python-3.x


    【解决方案1】:

    如果您可以将您的电话号码与模式匹配,则可以在替换中使用 \g<0> 反向引用来引用匹配值。

    因此,采用与您的电话号码匹配的最简单的模式,例如 \d+-\d+-\d+,您可以使用

    new_record = re.sub(r"\d+-\d+-\d+", r"+1-\g<0>", record)
    

    请参阅regex demo。在Find phone numbers in python script 上查看有关如何匹配电话号码的更多想法。

    Python demo

    import re
    def transform_record(record):
      new_record = re.sub(r"\d+-\d+-\d+", r"+1-\g<0>", record)
      return new_record
    
    print(transform_record("Some sample text 802-867-5309 some more sample text here"))
    # => Some sample text +1-802-867-5309 some more sample text here
    

    【讨论】:

      猜你喜欢
      • 2012-01-12
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 2012-10-04
      • 1970-01-01
      • 2023-01-19
      相关资源
      最近更新 更多