Replace Matches with Replacements Generated in Code (用函数作为替换体来替换匹配)

前端之家收集整理的这篇文章主要介绍了Replace Matches with Replacements Generated in Code (用函数作为替换体来替换匹配)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

需求:

将1 and 2 and 3变成2 and 4 and 6 (倍数关系)


方法

Python

def computereplacement(matchobj):

return str(int(matchobj.group()) * 2)


import re

subject = '1 and 2 and 3'

regobj = re.compile(r"\d+")

result = regobj.sub(computereplacement,subject)

print result


Tcl:

set pos 0 set subject "1 and 2 and 3" while {[regexp -indices -start $pos -linestop {\d+} $subject offsets]==1} { set pos [expr {1+[lindex $offsets 1]}] set start [lindex $offsets 0] set end [lindex $offsets 1] set element [string range $subject [lindex $offsets 0] [lindex $offsets 1]] set subject [string replace $subject $start $end [expr $element * 2]] } puts "subject:$subject"

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

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