Replace Matches with Replacements Generated in Code (用函数作为替换体来替换匹配)
2014-05-28 10:33
459 查看
需求:
将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"
将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"
相关文章推荐
- Validate Matches in Procedural Code (用程序码验证匹配)
- jQuery标签替换函数replaceWith()的使用例子
- Replace Matches Reusing Parts of the Match (替换重新使用部分匹配的匹配)
- Replace All Matches Between the Matches of Another (替换所有在匹配间的匹配)
- replace type code with class(重构)用类替换类型码
- jQuery标签替换函数replaceWith()的使用例子
- Replace All Matches Within the Matches of Another Regex (替换匹配中的匹配)
- Replace multiple spaces with one space in Python(替换多个空格为一个空格)
- Replace all spaces in string with ' ' (Cracking the Code Interview)
- 好文推荐:Development Tools and Techniques for Working with Code in Windows SharePoint Services 3.0
- C#不区分大小写的字符串替换(Replace)函数(转)
- Replace Type Code with Subclasses(以子类取代型别码)
- Replace the space in the string aa with "+"
- write solid code:不要使用output memory作为函数内使用的buffer
- JavaScript中的replace 达到replace.all函数替换的问题
- Working with windows in chrome code
- Replace Method with Method Object(以函数对象取代函数)
- Sybase中字符串替换函数:STR_REPLACE
- SQL中的REPLACE替换字符函数
- 利用webservice和.net技术上传和下载文件--Sending files in chunks with MTOM Web Services and .NET 2.0 from:http://www.codeproject.com/soap/MTO