我需要将子字符串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])
}
要在a
和first 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,"