user3766930 user3766930 - 2 months ago 6
Swift Question

what's wrong with this function to extract hashtags from string in Swift?

I have this extension:

extension String {
public func seperateHashtags(char : String) -> [String]{
var word : String = ""
var words : [String] = [String]()
for chararacter in self.characters {
if String(chararacter) == char && word != "" {
words.append(word)
word = char
}else {
word += String(chararacter)
}
}
words.append(word)
return words
}
}


and I want to get an array of hashtags from any given text.
I have a
UITextView
that contains the text:

write anything here... #one #two three #four


and I expect to have an output:

["one", "two", "four"]


but when I do this:

print(myTextView.text.seperateHashtags("#"))


I'm getting:

["write anything here... ", "#one ", "#two three ", "#four"]


how can I fix that?

Answer

You can use regx and get all the hashtag like this way.

var hastags = [String]()
var str = #one #two three #four"
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)")
    hastags.append(NSString(string: str).substringWithRange(NSRange(location:match.range.location + 1, length:match.range.length - 1)))
}

Output

["one", "two", "four"]