你的模式是错误的,你一开始就有[a-z],所以你没有检测到任何东西。
另外,NSStuff 更喜欢 utf16 计数(因为使用 NSString,它是 UTF16)
let myString = "Hi this is %1$s, product %2$s Hi this is %2$s, product %2$s"
let range = NSRange(location: 0, length: myString.utf16.count)
var regex = try! NSRegularExpression(pattern: "%(\\d+)\\$s", options: [])
var newStr = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "{$1}")
print(newStr)
输出:
$>Hi this is {1}, product {2} Hi this is {2}, product {2}
对 %(\d+)\$s 的一些解释(然后为 Swift 字符串重做 \)。
%:检测“%”
\d+:检测数字(包括 12 个不是你的之前的情况)
(\d+):检测号码,但在捕获组中
\$:检测“$”(需要转义,因为它是正则表达式中的特殊字符)
s:检测“ s"
所以有两组:整体(对应于整个正则表达式匹配)和数字。第一个是 0 美元,第二个是 1 美元,这就是我在模板中使用 {$1} 的原因。
注意:我使用https://regex101.com 来检查模式。
有了增量,你不能用模板来做。您必须枚举所有匹配项,进行操作并替换。
var myString = "Hi this is %1$s, product %2$s Hi this is %2$s, product %2$s"
let range = NSRange(location: 0, length: myString.utf16.count)
var regex = try! NSRegularExpression(pattern: "%(\\d+)\\$s", options: [])
let matches = regex.matches(in: myString, options: [] , range: range)
matches.reversed().forEach({ aMatch in
let fullNSRange = aMatch.range
guard let fullRange = Range(fullNSRange, in: myString) else { return }
let subNSRange = aMatch.range(at: 1)
guard let subRange = Range(subNSRange, in: myString) else { return }
let subString = myString[subRange]
guard let subInt = Int(subString) else { return }
let replacement = "{" + String(subInt + 1) + "}"
myString.replaceSubrange(fullRange, with: replacement)
})