简体   繁体   English

正则表达式匹配数字字符串中的 3 个零

[英]Regex to match 3 zeroes in the string of digits

Let's say I have strings like this one, and I need to get rid of three 0 in it.假设我有这样的字符串,我需要去掉其中的三个 0。 I need to get rid of the last three ones.我需要摆脱最后三个。 The numbers that should be created after removing these zeroes can consist only of 2 or 3 digits.删除这些零后应创建的数字只能包含 2 或 3 位数字。

Probably the best idea would be to somehow tell regex to only match when the pattern of 000 is followed by digits from [1-9] and exclude [1-9] from it.可能最好的主意是以某种方式告诉正则表达式仅在000的模式后跟来自[1-9]的数字并从中排除[1-9]时才匹配。 However, I have no idea how to do that.但是,我不知道该怎么做。

76000123000100000101000 ---> 76 123 100 101

Is it possible to do with regex?可以用正则表达式吗? I tried many different patterns, but I can't find the right one.我尝试了许多不同的模式,但我找不到合适的模式。

Use利用

re.sub(r'000(?=[1-9]|$)', ' ', x).strip()

See regex proof .请参阅正则表达式证明

EXPLANATION解释

--------------------------------------------------------------------------------
  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

Python code : Python 代码

import re
regex = r"000(?=[1-9]|$)"
test_str = "76000123000100000101000"
result = re.sub(regex, " ", test_str).strip()
print(result)

Results : 76 123 100 101结果76 123 100 101

Other options getting the last 3 zeroes are using a negative lookahead (?! asserting not a zero at the right.获得最后 3 个零的其他选项使用负前瞻(?!在右侧断言不是零。

000(?!0)

Regex demo |正则表达式演示| Python demo Python 演示

import re
 
print(re.sub(r'000(?!0)', ' ', '76000123000100000101000').strip())

Or using a capture group, matching 3 zeroes and capture what follows using that in the replacement:或者使用捕获组,匹配 3 个零并在替换中使用它捕获以下内容:

000([1-9]|$)

Regex demo |正则表达式演示| Python demo Python 演示

import re
 
print(re.sub(r'000([1-9]|$)', r'\1 ', '76000123000100000101000').strip())

Output Output

76 123 100 101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM