2

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?

JAL
  • 41,701
  • 23
  • 172
  • 300
Lucas Azzopardi
  • 1,131
  • 2
  • 11
  • 21
  • Objective-C answers here, but the logic applies the same way: [Number of occurrences of a substring in an NSString?](http://stackoverflow.com/questions/2166809/number-of-occurrences-of-a-substring-in-an-nsstring) – JAL Mar 02 '16 at 22:40

2 Answers2

8

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))}
nalexn
  • 10,615
  • 6
  • 44
  • 48
GetSwifty
  • 7,568
  • 1
  • 29
  • 46
1

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))}
Chatar Veer Suthar
  • 15,541
  • 26
  • 90
  • 154