1. 程式人生 > >Replace all Matches (替換所有匹配)

Replace all Matches (替換所有匹配)

需求:

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"