要用自身替换整个匹配项,可以使用替换后向引用
g<0>。但是,您要替换匹配并将其存储在变量中。您需要传递一个回调方法作为的替换参数
re.sub,并返回整个匹配值(
match.group()),并在该值后附加换行符:
import rematches = [] # Variable to hold the matchesdef repl(m): # m is a match data object matches.append(m.group()) # Add a whole match value return "{}n".format(m.group()) # Return the match and a newline appended to its = 'I want to be able to replace many words, especially in this sentence, since it will help me solve by problem. That makes sense right?'pattern = re.compile(r'words[,]|sentence[,]|problem[.]')s = re.sub(pattern, repl, s)print(s)print(matches)
参见Python演示
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)