用re.sub向数字串中添加+1。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用re.sub向数字串中添加+1。相关的知识,希望对你有一定的参考价值。

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

当我使用下面的函数时,它将这个字符串 "802-867-5309 "改为这个字符串 "+1+15309"。我试图得到这个字符串 "+1-802-867-5309"。docs replace中的例子显示了如何替换整个字符串,我不想替换整个字符串,只想附加一个+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"))
答案

如果你可以用一个模式来匹配你的电话号码,你可以用以下方法来参考匹配值。g<0> 替换中的backreference。

所以,以最简单的模式,如 d+-d+-d+ 匹配您的电话号码,您可以使用

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

搜索引擎演示. 查看更多关于如何匹配电话号码的想法在 用python脚本查找电话号码.

Python演示:

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

以上是关于用re.sub向数字串中添加+1。的主要内容,如果未能解决你的问题,请参考以下文章

re.sub的使用方法有哪些?

字符串删除指定符号(不限位置)

re.sub()介绍和用法

re.sub用法

python re.sub 组:\number 之后的数字

为啥 re.sub() 在 Python 中默认添加不匹配的字符串?