在不使用 NSRegularExpression 的情况下,如何获取字符串正则表达式的所有匹配项?

Without using NSRegularExpression, How can I get all matches of my string regular expression?

Swift3 介绍String.range(of:options)。然后,使用此函数,可以在不创建 NSRegularExpression 对象的情况下匹配字符串的一部分,例如:

let text = "it is need #match my both #hashtag!"
let match = text.range(of: "(?:^#|\s#)[\p{L}0-9_]*", options: .regularExpression)!

print(text[match]) //  #math

但是,是否可以同时匹配出现的正则表达式(即 #match#hashtag),而不是只匹配第一个?

let text = "it is need #match my both #hashtag!"
// create an object to store the ranges found
var ranges: [Range<String.Index>] = []
// create an object to store your search position
var start = text.startIndex
// create a while loop to find your regex ranges
while let range = text.range(of: "(?:^#|\s#)[\p{L}0-9_]*", options: .regularExpression, range: start..<text.endIndex) {
    // append your range found
    ranges.append(range)
    // and change the startIndex of your string search
    start = range.lowerBound < range.upperBound ? range.upperBound : text.index(range.lowerBound, offsetBy: 1, limitedBy: text.endIndex) ?? text.endIndex
}
ranges.forEach({print(text[[=10=]])})

这将打印

#匹配

#话题标签

如果您需要在代码中多次使用它,您应该将此扩展添加到您的项目中:

extension StringProtocol {
    func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<Index>] {
        var result: [Range<Index>] = []
        var start = startIndex
        while start < endIndex,
            let range = self[start...].range(of: string, options: options) {
            result.append(range)
            start = range.lowerBound < range.upperBound ?
                    range.upperBound : index(after: range.lowerBound)
        }
        return result
    }
}

用法:

let text = "it is need #match my both #hashtag!"
let pattern = "(?<!\S)#[\p{L}0-9_]*"
let ranges = text.ranges(of: pattern, options: .regularExpression)
let matches = ranges.map{text[[=12=]]}
print(matches)  // ["#match", "#hashtag"]