[英]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
上面的代碼不好,原因有兩個:
如果m.group(0)恰好包含任何正則表達式特殊字符(例如*,+等),則此方法將不起作用。
感覺就像我在重復工作:首先我在字符串中搜索正則表達式,然后我不得不再次尋找它以將其刪除。
有什么好方法嗎?
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.