Python 3.x 一般表达式Re.sub()
我写了这段代码:Python 3.x 一般表达式Re.sub(),python-3.x,regex,re,Python 3.x,Regex,Re,我写了这段代码: result= re.sub(r"\s\d{3}",r"\0","My phone number is 999-582-9090") print(result) 已获得输出: My phone number is( )-582-9030 为什么我的号码没有打印出来? 感谢您的帮助您可以尝试: \s+(\d{3})(?=-) 对上述正则表达式的解释: \s+-表示一个或多个空白字符 \d{3}-表示捕获前3位数字的捕获组 ?=--表示正向前瞻,仅在a-之前声明三位数字 您可
result= re.sub(r"\s\d{3}",r"\0","My phone number is 999-582-9090")
print(result)
已获得输出:
My phone number is( )-582-9030
为什么我的号码没有打印出来?
感谢您的帮助您可以尝试:
\s+(\d{3})(?=-)
对上述正则表达式的解释:
\s+-表示一个或多个空白字符
\d{3}-表示捕获前3位数字的捕获组
?=--表示正向前瞻,仅在a-之前声明三位数字
您可以在中找到演示
python实现:
您可以在中找到上述代码的示例运行,您的预期结果是什么?@user202729-我想这是显而易见的;我的电话号码是999-582-9030@user202729这是我的电话号码999-582-9030
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)