首页 > 解决方案 > 正则表达式匹配数字字符串中的 3 个零

问题描述

假设我有这样的字符串,我需要去掉其中的三个 0。我需要摆脱最后三个。删除这些零后应创建的数字只能包含 2 或 3 位数字。

可能最好的主意是以某种方式告诉正则表达式仅在模式000后跟数字时匹配[1-9]并从中排除[1-9]。但是,我不知道该怎么做。

76000123000100000101000 ---> 76 123 100 101

可以用正则表达式吗?我尝试了许多不同的模式,但我找不到合适的模式。

标签: pythonregex

解决方案


采用

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


推荐阅读