快速获取字符串中子字符串的所有范围 [英] get all ranges of a substring in a string in swift

查看:88
本文介绍了快速获取字符串中子字符串的所有范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,例如"ab ad adk fda kla kad ab ab kd".我想获取所有范围的ab.(这里ab位于3位置,所以我应该获得3范围).在正常情况下,我的代码工作正常,但是如果搜索文本为.",那么我得到错误的结果

I have a string for example "ab ad adk fda kla kad ab ab kd". I want to get all range of ab.(Here ab is present at 3 position so I should get 3 range).In normal scenarion my code is working fine, but if search text is ".",then I am getting wrong result

do {
    let regEx = try NSRegularExpression(pattern: searchText, options: NSRegularExpressionOptions.CaseInsensitive)

    let matchesRanges = regEx.matchesInString(attributedText.string, options:[], range: NSMakeRange(0, attributedText.string.length))

    for rng in matchesRanges {
        let wordRange = rng.rangeAtIndex(0)
    }
} catch {
    ...
}

推荐答案

以下解决方案使用本机Swift 4函数range(of:, options:, range:, locale:)):

The following solution uses the native Swift 4 function range(of:, options:, range:, locale:)):

extension String {
    func ranges(of substring: String, options: CompareOptions = [], locale: Locale? = nil) -> [Range<Index>] {
        var ranges: [Range<Index>] = []
        while ranges.last.map({ $0.upperBound < self.endIndex }) ?? true,
            let range = self.range(of: substring, options: options, range: (ranges.last?.upperBound ?? self.startIndex)..<self.endIndex, locale: locale)
        {
            ranges.append(range)
        }
        return ranges
    }
}

(然后Swift 4提供了本机API,可以从Range<Index>转换为NSRange)

(Swift 4 then provides native API to convert from Range<Index> to NSRange)

这篇关于快速获取字符串中子字符串的所有范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆