user3766930 user3766930 - 1 year ago 56
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 != "" {
word = char
}else {
word += String(chararacter)
return words

and I want to get an array of hashtags from any given text.
I have a
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:


I'm getting:

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

how can I fix that?

Answer Source

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)))


["one", "two", "four"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download