繁体   English   中英

python正则表达式匹配并替换

[英]python regex match and replace

我需要查找,处理和删除(一个一个地)匹配相当长的正则表达式的子字符串:

# 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

上面的代码不好,原因有两个:

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

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

有什么好方法吗?

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)

暂无
暂无

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

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