【发布时间】:2014-11-29 10:36:18
【问题描述】:
我喜欢使用正则表达式将“我跑了 12 英里”改为“我跑了 24 英里”。 “12”可以是任何数字。我使用函数“replace2()”进行数学运算。传递给函数 replace2("$1") 的捕获参数 "$1" 很好。请帮忙!
func replace( str:String, pattern : String, repl:String)->String?{
let regex = NSRegularExpression .regularExpressionWithPattern(pattern, options: nil,error: nil)
let replacedString = regex.stringByReplacingMatchesInString( str, options: nil,
range: NSMakeRange(0, countElements( str)), withTemplate: repl )
return replacedString
}
replace( "I run 12 miles and walk 12.45 km","\\d+(.\\d+)?", "-")!
func replace2(x: String)->String {
let xx = x.toInt()! * 2 // error : return nil?
return String(format: "\(xx)")
}
replace( "I run 12 miles ","(\\d+)", replace2("$1") )! // error
【问题讨论】: