首页 > 解决方案 > 一般表达式 Re.sub()

问题描述

我写了这段代码:

result= re.sub(r"\s\d{3}",r"\0","My phone number is 999-582-9090")
print(result)

得到输出:

My phone number is( )-582-9030

为什么我的号码没有打印出来?谢谢您的帮助

标签: python-3.xregexre

解决方案


你可以试试:

\s+(\d{3})(?=-)

上述正则表达式的解释:

\s+- 代表一个空白字符一次或多次。

(\d{3})- 表示捕获前 3 位数字的捕获组。

(?=-)- 表示仅在 a 之前断言三位数字的正向前瞻-

图形表示

你可以在这里找到演示。

在python中的实现:

import re

regex = r"\s+(\d{3})(?=-)"

test_str = "My phone number is 999-582-9090"

subst = " (\\1)"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

您可以在此处找到上述代码的示例运行。


推荐阅读