python-3.x - 一般表达式 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
为什么我的号码没有打印出来?谢谢您的帮助
解决方案
你可以试试:
\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)
您可以在此处找到上述代码的示例运行。
推荐阅读
- visual-studio - 如何调试 Microsoft Store 包?
- node.js - 为什么使用`yarn link`?为什么不只是 node_modules 中的符号链接?
- r - 如何防止在缺失数据行数超过 X 的值之间进行插值?
- c++ - 如何使用重载运算符修复此内存泄漏?
- maven - GlassFish/Payara - 定义的 maven 依赖抛出 ClassNotFoundException
- python - 如何根据特定的字符串值从 Excel 电子表格中提取工作表的内容
- php - 如何在 php Symfony 中将 XML 反序列化为包含数组集合的对象
- csv - 从 Google 表格加载 CSV 文件
- javascript - D3 无法加载自定义 geojson 数据
- c++ - 使用 Turbo C 和 GNU C/C++ 有什么区别?