python正则表达式匹配和替换

max*_*max 17 python regex

我需要找到,处理和删除(逐个)任何匹配相当长的正则表达式的子串:

# p is a compiled regex
# s is a string  
while 1:
    m = p.match(s)
    if m is None:
        break
    process(m.group(0)) #do something with the matched pattern
    s = re.sub(m.group(0), '', s) #remove it from string s
Run Code Online (Sandbox Code Playgroud)

上面的代码有两个原因:

  1. 如果m.group(0)恰好包含任何正则表达式特殊字符(如*,+等),则不起作用.

  2. 感觉就像我正在重复工作:首先我在字符串中搜索正则表达式,然后我必须再次寻找它以删除它.

这样做的好方法是什么?

Mar*_*ers 20

应用re.sub函数可以接受一个函数作为参数,所以你可以,如果你想结合的置换和处理步骤:

# p is a compiled regex
# s is a string  
def process_match(m):
    # Process the match here.
    return ''

s = p.sub(process_match, s)
Run Code Online (Sandbox Code Playgroud)