一般表达式 Re.sub()
General Expression Re.sub()
我写了这段代码:
result= re.sub(r"\s\d{3}",r"[=11=]","My phone number is 999-582-9090")
print(result)
得到输出:
My phone number is( )-582-9030
为什么我的号码没有打印出来?
感谢帮助
你可以试试:
\s+(\d{3})(?=-)
上面正则表达式的解释:
\s+
- Represents a whitespace character one or more times.
(\d{3})
- Represents a capturing group capturing first 3 digits.
(?=-)
- Represents a positive lookahead asserting the three digits only before a -
.
您可以在 here.
中找到演示
在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)
您可以在here.
中找到上述代码的示例运行
我写了这段代码:
result= re.sub(r"\s\d{3}",r"[=11=]","My phone number is 999-582-9090")
print(result)
得到输出:
My phone number is( )-582-9030
为什么我的号码没有打印出来? 感谢帮助
你可以试试:
\s+(\d{3})(?=-)
上面正则表达式的解释:
\s+
- Represents a whitespace character one or more times.
(\d{3})
- Represents a capturing group capturing first 3 digits.
(?=-)
- Represents a positive lookahead asserting the three digits only before a-
.
您可以在 here.
中找到演示在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)
您可以在here.
中找到上述代码的示例运行