20

I have AttributedString with emoji like this " @Mervin tester "

Now I need to find a range of Mervin in this attributed String.

let attributedString = NSMutableAttributedString(string: " @Mervin tester ")

let range = // range for "Mervin" in above String. 

Thank you.

Yaman
  • 1,030
  • 17
  • 33
Ujesh
  • 1,698
  • 2
  • 23
  • 35
  • 2
    Do you know `Mervin`? Or you are looking for `@SomeName`? Else, `let range = attributedString.string.rangeOfString("Marvin")` (in pseudo code, I'm not sure of the Swift methods names, but completion should help you). – Larme Jun 29 '17 at 08:27
  • @Larme Thank you, it's working. I was trying same with utf-8 string so it was showing the wrong result. – Ujesh Jun 29 '17 at 13:05

2 Answers2

23

This extension should help you.

extension NSAttributedString {
    func rangeOf(string: String) -> Range<String.Index>? {
        return self.string.range(of: string)
    }
}

Usage:

attributedString.rangeOf(string: "Mervin")
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
-1

I wanted something similar but for AttributedString instead. It took me a while to find the solution, so I think I may document it here since this is the first search hit for my question.

let attributedString = AttributedString(" @Mervin tester ")
let substring = "Mervin"

// Iterating through all the occurrences of `substring`.
for range in attributedString.characters.ranges(of: substring) {
   // Do something with the current range
   attributedString[range].foregroundColor = .red
}
Bogdan Farca
  • 3,856
  • 26
  • 38