Replace all Matches (替换所有匹配)

前端之家收集整理的这篇文章主要介绍了Replace all Matches (替换所有匹配)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

需求:

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"

猜你在找的正则表达式相关文章