1

I'm looking for a way to get the ranges from a regex match. I have a string

I'm looking for @{1 | Tom Lofe} and @{2 | Cristal Dawn}

From this string, I need to get the ranges of these matches using the following regex

"@\\{(\\d+) ?\\| ?(\\w+ *?\\w*?)\\}"

What is the best way to do this? So far I've only been able to get the matches but not the ranges. Apparently, the standard Swift function range(of: <#T##StringProtocol#>, options: <#T##String.CompareOptions#>, range: <#T##Range<String.Index>?#>, locale: <#T##Locale?#>) should be able to do this, but I don't know how to use it, and can't seem to find a good example.

I've also tried this question's answer get all ranges of a substring in a string in swift but again am unable to get it to work.

wp78de
  • 18,207
  • 7
  • 43
  • 71
Riyan Fransen
  • 534
  • 1
  • 3
  • 14
  • Have a look at https://stackoverflow.com/questions/27880650/swift-extract-regex-matches – Martin R Apr 25 '18 at 10:58
  • https://stackoverflow.com/questions/32305891/index-of-a-substring-in-a-string-with-swift You can use `ranges(of:)` with `options: .regularExpression` – Leo Dabus Apr 25 '18 at 11:13
  • Are you happy to mark my answer as correct as, I believe, it satisfies your original question and the subsequent variant raised. Thanks. Good question, by the way. – Scott McKenzie Apr 26 '18 at 07:30

1 Answers1

2

This works in an Xcode Playground, but let me know if it doesn't work for you.

let regex = try! NSRegularExpression(pattern: "@\\{(\\d+) ?\\| ?(\\w+ *?\\w*?)\\}", options: [])

let input = "I'm looking for @{1 | Tom Lofe} and @{2 | Cristal Dawn}"
let range = NSRange(location: 0, length: input.utf16.count)

for match in regex.matches(in: input, options: [], range: range) {
    print(match.range)
}

Prints:

{16, 15}
{36, 19}
Scott McKenzie
  • 16,052
  • 8
  • 45
  • 70
  • Try this with `let input = "I'm looking for @{1 | Tom Lofe} and @{2 | Cristal Dawn}"` – Martin R Apr 25 '18 at 12:50
  • I’m not sure I understand, @MartinR Is this is a different question now? – Scott McKenzie Apr 25 '18 at 12:56
  • @ScottMcKenzie you are using the wrong value for the length. you need to pass the utf16 count. `NSRange(location: 0, length: input.utf16.count)` – Leo Dabus Apr 25 '18 at 12:56
  • Did you try it? Did you notice that only one range is printed? – You'll find an explanation in https://stackoverflow.com/a/27880748/1187415 – Martin R Apr 25 '18 at 12:57
  • @ScottMcKenzie Well I am showing to you what's wrong in your code. Feel free to keep your answer as it is if you would like to. Btw , `options: []` is the default value therefore you can just omit it. – Leo Dabus Apr 25 '18 at 13:00
  • Sorry @LeoDabus, I get that. But my answer was for the original question. Updating for unicode characters is, as you say. Answer amended. – Scott McKenzie Apr 25 '18 at 13:07
  • @MartinR Try now. – Scott McKenzie Apr 25 '18 at 13:07