Reputation: 1181
I have been looking around for some time now and am wondering how to detect multiple locations of a substring within a larger string. For example:
let text = "Hello, playground. Hello, playground"
let range: Range<String.Index> = text.rangeOfString("playground")! //outputs 7...<17
let index: Int = text.startIndex.distanceTo(range.startIndex) //outputs 7, the location of the first "playground"
I use this code to detect the first location that the substring appears within a string, but its it possible to detect the location of the second occurrence of "playground" and then the third and so on and so forth?
Upvotes: 2
Views: 1612
Reputation: 7746
This should get you an array of NSRanges with "playground"
let regex = try! NSRegularExpression(pattern: "playground", options: [.caseInsensitive])
let items = regex.matches(in: text, options: [], range: NSRange(location: 0, length: (text as NSString).length))
let ranges: [NSRange] = items.map{$0.range}
Then to get the strings:
let occurrences: [String] = ranges.map{String((text as NSString).substring(with:$0))}
Upvotes: 8
Reputation: 15639
Swift 4
let regex = try! NSRegularExpression(pattern: fullNameArr[1], options: [.caseInsensitive])
let items = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.count))
let ranges: [NSRange] = items.map{$0.range}
let occurrences: [String] = ranges.map{String((str as NSString).substring(with: $0))}
Upvotes: 1