如何将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)
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)
| 归档时间: |
|
| 查看次数: |
928 次 |
| 最近记录: |