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 range(_:)
function.
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.
EDIT
If you want to know how to do this with emojis to, go here