您的模式是正确的,但您的代码未编译。请改用以下代码:
Swift 4
let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
var results = [String]()
regex.enumerateMatches(in: query, options: [], range: NSMakeRange(0, query.utf16.count)) { result, flags, stop in
if let r = result?.range(at: 1), let range = Range(r, in: query) {
results.append(String(query[range]))
}
}
print(results)
NSString
使用UTF-16编码,因此NSMakeRange
应该使用UTF-16代码单元的数量调用。
Swift 2
let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
let tmp = query as NSString
var results = [String]()
regex.enumerateMatchesInString(query, options: [], range: NSMakeRange(0, tmp.length)) { result, flags, stop in
if let range = result?.rangeAtIndex(1) {
results.append(tmp.substringWithRange(range))
}
}
print(results)
从Swift本身的String
类型中获取子字符串有些麻烦。这就是为什么我将query
转换为NSString
的原因。
query
、characters.count
和matchesInString
都是非可选类型,如果第一个可选绑定成功,regex
就会被解包。除此之外,在这种特定的情况下,你永远不应该使用try!
。 - vadian