【发布时间】:2021-04-08 15:46:39
【问题描述】:
在应用程序中我有类似的字符串
1A11A1
我想把它转换成
1A1 1A1
3个字符后应该有空格。
我尝试的是:代码 = 1A11A1
let end = code.index(code.startIndex, offsetBy: code.count)
let range = code.startIndex..<end
if code.count < 3 {
code = code.replacingOccurrences(of: "(\\d+)", with: "$1", options: .regularExpression, range: range)
}
else {
code = code.replacingOccurrences(of: "(\\d{3})(\\d+)", with: "$1 $2", options: .regularExpression, range: range)
}
【问题讨论】:
-
您可以只匹配单词字符而不是数字
(\\w{3})(\\w+)并替换为两组$1 $2或(?<!\\S)(\\w{3})(\\w+)