python 正则匹配和替换
我需要找到、处理并逐个移除一些符合比较长的正则表达式的子字符串:
# 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
上面的代码有两个问题:
如果 m.group(0) 里面包含一些正则表达式的特殊字符(比如 *, + 等),那就不管用了。
感觉我在重复工作:我先要在字符串里找出正则表达式,然后还得再去找一次把它移除。
有什么好的方法可以做到这一点吗?
1 个回答
21
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)