简体   繁体   English

当前面有数字时递归匹配每个非数字字符

[英]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.

相关问题 将列表中的每个字符串拆分为数字和非数字部分 - Split each string in a list into digit and non-digit parts 在熊猫数据框中的某些字符之前提取非数字字符 - Extract non-digit characters before certain character in pandas dataframe 用'.'分割当前面没有数字时 - Split by '.' when not preceded by digit 删除Python中第一个非数字之后(包括第一个非数字)的所有非正则表达式的最佳方法 - Best non-regex way to remove all characters after and including the first non-digit in Python 如何仅在特定字符串后才匹配数字,如果发现非数字则停止匹配-Python 27 - How to match digits only after a particular string, stop matching if non-digit is found - Python 27 如何告诉python 3跳过csv文件中的非数字字符 - how to tell python 3 to skip over non-digit characters from a csv file Pandas DataFrame:删除非数字字符后的所有内容 - Pandas DataFrame: Remove everything after a non-digit character Pyparsing:带有至少一个非数字字符的单词 - Pyparsing: word with at least one non-digit character 在Python中使用.find查找第一个非数字字符 - Finding first non-digit character with .find in Python 如何将字符串(带有非数字位值分隔符)转换为整数? - How to convert a string (with non-digit place value separators) into an integer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM