Tometoyou Tometoyou - 25 days ago 4x
iOS Question

How to get range of specific substring even if a duplicate

I want to detect the words that begin with a

, and return their specific ranges. Initially I tried using the following code:

for word in words {
if word.hasPrefix("#") {
let matchRange = theSentence.range(of: word)
//Do stuff with this word

This works fine, except if you have a duplicate hashtag it will return the range of the first occurrence of the hashtag. This is because of the nature of the

Say I have the following string:

"The range of #hashtag should be different to this #hashtag"

This will return
(13, 8)
for both hashtags, when really it should return
(13, 8)
as well as
(50, 8)
. How can this be fixed? Please note that emojis should be able to be detected in the hashtag too.


If you want to know how to do this with emojis to, go here


Create regex for that and use it with the NSRegularExpression and find the matches range.

var str = "The range of #hashtag should be different to this #hashtag"
let regex = try NSRegularExpression(pattern: "(#[A-Za-z0-9]*)", options: [])
let matches = regex.matchesInString(str, options:[], range:NSMakeRange(0, str.characters.count))
for match in matches {
    print("match = \(match.range)")