Replace All Matches Within the Matches of Another Regex (替换匹配中的匹配)

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

需求:

将位于<b></b>之间的before替换为after

eg.

before <b>first before</b> before <b>before before</b>

变成

before <b>first after</b> before <b>after after</b>


Python:

import re

subject = "before <b>first before</b> before <b>before before</b>"

innerre = re.compile("before")

def replacewithin(matchobj):

return innerre.sub("after",matchobj.group())


result = re.sub("<b>.*</b>",replacewithin,subject)

print result


Tcl:

set subject "before <b>first before</b> before <b>before before</b>" set pos 0 while {[regexp -nocase -indices -start $pos {<b>(.*?)</b>} $subject offsets]==1} { set bOffSets $offsets set pos [expr {1+[lindex $offsets 1]}] set sTmp [string range $subject [lindex $offsets 0] [lindex $offsets 1]] set ios 0 while {[regexp -indices -start $ios -linestop {(before)} $sTmp offsets]==1} { set ios [expr {1+[lindex $offsets 1]}] set start [lindex $offsets 0] set end [lindex $offsets 1] set element [string range $sTmp [lindex $offsets 0] [lindex $offsets 1]] set sTmp [string replace $sTmp $start $end "after"] } set subject [string replace $subject [lindex $bOffSets 0] [lindex $bOffSets 1] $sTmp] } puts "subject:$subject"

原文链接:https://www.f2er.com/regex/361691.html

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