如何通过swift macos从主字符串中分离辅助字符串?



我需要将子字符串bc与主字符串分开,但返回的结果是:bc,d,e,f

let tokenx = "123 abc,d,e,f,"
let regex = try NSRegularExpression(pattern: "a(.*),")
let matches = regex.matches(in: tokenx, range: NSRange(tokenx.startIndex..., in: tokenx))
for match in matches {
let swiftRange = Range(match.range(at: 1), in: tokenx)!
print(tokenx[swiftRange])
}

要在afirst comma之间分隔任何,您必须搜索一个或多个不是逗号的字符在括号内([^,]+)

let tokenx = "123 abc,d,e,f,"
let regex = try NSRegularExpression(pattern: "a([^,]+)")
let matches = regex.matches(in: tokenx, range: NSRange(tokenx.startIndex..., in: tokenx))
for match in matches {
let swiftRange = Range(match.range(at: 1), in: tokenx)!
print(tokenx[swiftRange])
}
更具体的模式是"a([^,]+),d,e,f,"

最新更新