需求:
a. 将before and before and before变成afterand after and after(替换所有的before为after)
b. 将before and before and before变成afterand 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"