Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 一般表达式Re.sub()_Python 3.x_Regex_Re - Fatal编程技术网

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)