How to find Multiple NSRange for a string from full string iOS swift

痞子三分冷 提交于 2019-12-23 22:15:14

问题


let fullString = "Hello world, there are \(string(07)) continents and \(string(195)) countries."
let range = [NSMakeRange(24,2), NSMakeRange(40,3)]

Need to find the NSRange for numbers in the entire full string and there is a possibility that both numbers can be same. Currently hard coding like shown above, the message can be dynamic where hard coding values will be problematic.

I have split the strings and try to fetch NSRange since there is a possibility of same value. like stringOne and stringTwo.

func findNSMakeRange(initialString:String, fromString: String) {
        let fullStringRange = fromString.startIndex..<fromString.endIndex
        fromString.enumerateSubstrings(in: fullStringRange, options: NSString.EnumerationOptions.byWords) { (substring, substringRange, enclosingRange, stop) -> () in
            let start = distance(fromString.startIndex, substringRange.startIndex)
            let length = distance(substringRange.startIndex, substringRange.endIndex)
            let range = NSMakeRange(start, length)

            if (substring == initialString) {
                print(substring, range)
            }
        })
    }

Receiving errors like Cannot invoke distance with an argument list of type (String.Index, String.Index)

Anyone have any better solution ?


回答1:


Another approach is to define an extension to return an array of ranges, i.e. [Range<String.Index>]:

extension StringProtocol where Index == String.Index {
    func ranges<T: StringProtocol>(of string: T, options: String.CompareOptions = []) -> [Range<Index>] {
        var ranges: [Range<Index>] = []
        var start: Index = startIndex

        while let range = range(of: string, options: options, range: start..<endIndex) {
            ranges.append(range)
            start = range.upperBound
        }

        return ranges
    }
}

Then you can use it like so:

let string = "Hello world, there are 09 continents and 195 countries."
let ranges = string.ranges(of: "[0-9]+", options: .regularExpression)

So, for example, if you wanted to make these numbers bold in some attributed string:

string.ranges(of: "[0-9]+", options: .regularExpression)
    .map { NSRange($0, in: string) }
    .forEach {
        attributedString.setAttributes(boldAttributes, range: $0)
}


来源:https://stackoverflow.com/questions/49184837/how-to-find-multiple-nsrange-for-a-string-from-full-string-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!