[英]Recursively matching each non-digit characters when preceded by a digit
I'm trying to match each individual non-digit characters that are directly preceded by a digit.我正在尝试匹配每个直接以数字开头的非数字字符。 The idea is to replace
O
with 0
in numbers.这个想法是用数字
0
替换O
Eg:例如:
58OO
1O1O
2OOOm
FOO
O
The desired output is所需的 output 是
5800
1010
2000m
FOO
O
I tried using the answer in a previous question I asked but I don't manage to adapt the regex to my purpose.我尝试在我问的上一个问题中使用答案,但我没有设法使正则表达式适应我的目的。
Here are a few regex I tried, without success (and for good reasons): (\d\K(?>O|(?1)))
or \d\K(?:O|(?R))
.这是我尝试的一些正则表达式,但没有成功(并且有充分的理由):
(\d\K(?>O|(?1)))
或\d\K(?:O|(?R))
。
Nothing to do with recursion, just use a simple while loop:与递归无关,只需使用一个简单的while循环:
import re
strings = ["58OO", "1O1O", "2OOOm", "FOO", "O"]
pattern = re.compile(r'(?<=\d)O')
for item in strings:
while True:
olditem = item
item = pattern.sub("0", item)
if item == olditem:
# no replacement was made
break
print(item)
This yields这产生
5800
1010
2000m
FOO
O
Time to install PyPi regex module :是时候安装PyPi 正则表达式模块了:
import regex
texts = ["58OO", "1O1O", "2OOOm", "FOO", "O"]
for text in texts:
print( regex.sub(r'(?<=\d+O*)O', '0', text) )
Output: Output:
5800
1010
2000m
FOO
O
The (?<=\d+O*)O
expression matches O
that has digit(s) and any amount of O
s before. (?<=\d+O*)O
O
匹配之前有数字和任意数量的O
的 O 。
A simple sub is more than enough.一个简单的潜艇就足够了。
Example from the python
interpreter: python
解释器的示例:
>>> import re
>>> raw = '''
58OO
O1O1O
2OOOm
FOO
O
'''
>>>
>>> print(re.sub(r'(\d+)(O+)', lambda m: m.group(1) + '0' * len(m.group(2)), raw))
5800
O1010
2000m
FOO
O
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.