python替换所有匹配的例子

发布时间:2020-04-11编辑:脚本学堂
本文介绍了python正则表达式替换所有匹配的方法,python使用正则替换所有匹配内容的例子,需要的朋友参考下。

python使用正则表达式替换文件内容。

需求描述:
a. 将before and before and before变成after and after and after (替换所有的before为after)
b. 将before and before and before变成after and after and before  (替换前两个before为after)

操作方法:
1. Python
a.
 

复制代码 代码示例:
import re
subject = "before and before and before"
reobj = re.compile('before')
result = reobj.sub("after", subject)
print result

b.
 

复制代码 代码示例:
import re
subject = "before and before and before"
reobj = re.compile('before')
result = reobj.sub("after", subject, 2)
print result

2. Tcl
a.
 

复制代码 代码示例:
set subject "before and before and before"
regsub -all "before" $subject "after" result
puts "$result"

b.
 

复制代码 代码示例:

set subject "before and before and before"
regsub "before" $subject "after" result
for {set i 0} {$i < [expr 2 - 1]} {incr i} {

    regsub "before" $result "after" result
}
puts "$result"