python - 正则表达式匹配数字字符串中的 3 个零
问题描述
假设我有这样的字符串,我需要去掉其中的三个 0。我需要摆脱最后三个。删除这些零后应创建的数字只能包含 2 或 3 位数字。
可能最好的主意是以某种方式告诉正则表达式仅在模式000
后跟数字时匹配[1-9]
并从中排除[1-9]
。但是,我不知道该怎么做。
76000123000100000101000 ---> 76 123 100 101
可以用正则表达式吗?我尝试了许多不同的模式,但我找不到合适的模式。
解决方案
采用
re.sub(r'000(?=[1-9]|$)', ' ', x).strip()
请参阅正则表达式证明。
解释
--------------------------------------------------------------------------------
000 '000'
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
[1-9] any character of: '1' to '9'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
$ before an optional \n, and the end of
the string
--------------------------------------------------------------------------------
) end of look-ahead
蟒蛇代码:
import re
regex = r"000(?=[1-9]|$)"
test_str = "76000123000100000101000"
result = re.sub(regex, " ", test_str).strip()
print(result)
结果:76 123 100 101
推荐阅读
- functional-programming - 了解 OCaml Lwt.return_unit
- android - err_cert_authority_invalid - 自签名 CA 在 android 上无效,但在 PC 上有效
- javascript - 调用 Dialogflow API 时如何指定代理 ID?
- r - 识别组内重复值的第一个实例
- javascript - 用javascript自动填写表格
- javascript - getImageData:无法从画布获取图像数据,因为画布已被跨域数据污染
- c++ - 使用 std::bind 绑定函数的问题
- redis - 我们如何实现拒绝对 redis 缓存的旧更新
- php - 重命名数据:图像/webp;base64,php 中的文件(Imagick)
- php - Ajax 表单提交可视化 php 文件