import Foundation
let pattern = #"「\S*?」"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
忽聽得遠處嘯聲又起,一個聲音叫道:「西山一窟鬼奉神鵰俠之令,來向郭二姑娘祝壽,恭獻壽禮。」聲音尖細,若斷若續,但人人聽得十分清楚。
郭靖見第一件壽禮實在太大,忙提聲叫道:「郭靖謹候台駕。他話聲渾厚和平,遠遠傳送出去,跟著走到大校場入口處相迎。
黃蓉和他並肩而立,低聲道:「你猜這神鵰俠是誰?郭靖道:「我猜不出。」黃蓉道:「便是楊過!」郭靖一呆,隨即滿心歡暢,說道:「了不起,了不起!他立下如此奇功,當真是大宋之福。」黃蓉道:「你猜他第二件壽禮是甚麼?」郭靖微笑道:「過兒才智卓絕,只有你方勝得了他,也只有你,才猜得中他的心思。」黃蓉道:「這一次我可猜不中了。」心想:「楊過為襄陽立此大功,但口口聲聲說是為了襄兒,他對我夫婦與芙兒的怨恨可絲毫未消。」
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression