如何替换Swift中的第一次出现?

cod*_*ife 6 regex swift

如何将replacementOccurrences与regex一起使用并仅替换第一次出现?

var str = "= 1 = 2 = 3"
str = str.replacingOccurrences(of: "(\\d+)", with: "\\\\$1", options: .regularExpression)
// prints: = \\1 = \\2 = \\3
// should print: = \\1 = 2 = 3
Run Code Online (Sandbox Code Playgroud)

Cod*_*ent 5

String.range() 将在第一场比赛停止:

var str = "= 1 = 2 = 3"
if let range = str.range(of: "\\d+", options: .regularExpression) {
    let substr = str[range]
    str = str.replacingCharacters(in: range, with: "\\\\" + substr)
}

print(str)
Run Code Online (Sandbox Code Playgroud)