正则表达式模式在 Swift 中匹配和替换



我有如下字符串:

Hi this is %1$s, product %2$sHi this is %2$s, product %2$s

我想用{0}代替%1$s,用{1}替换%2$s等等。

我试图使:

let range = NSRange(location: 0, length: myString.count)
var regex = try! NSRegularExpression(pattern: "%[1-9]\$s", options: [])
var newStr = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "XXXX")

任何人都可以帮助我,拜托!

你的模式是错误的,你在开始时有[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)
})

最新更新