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.

3
  • Have a look at stackoverflow.com/questions/27880650/… Commented Apr 25, 2018 at 10:58
  • stackoverflow.com/questions/32305891/… You can use ranges(of:) with options: .regularExpression Commented Apr 25, 2018 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. Commented Apr 26, 2018 at 7:30

1 Answer 1

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}
Sign up to request clarification or add additional context in comments.

7 Comments

Try this with let input = "😳I'm looking for @{1 | Tom Lofe} and @{2 | Cristal Dawn}"
I’m not sure I understand, @MartinR Is this is a different question now?
@ScottMcKenzie you are using the wrong value for the length. you need to pass the utf16 count. NSRange(location: 0, length: input.utf16.count)
Did you try it? Did you notice that only one range is printed? – You'll find an explanation in stackoverflow.com/a/27880748/1187415
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.