user3766930
user3766930

Reputation: 5839

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?

Upvotes: 0

Views: 856

Answers (2)

Nirav D
Nirav D

Reputation: 72460

You can use regex and get all the hashtag like this way:

var hashtags = [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)")
    hashtags.append(NSString(string: str).substringWithRange(NSRange(location:match.range.location + 1, length:match.range.length - 1)))
}

Output:

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

Upvotes: 6

WojciechBilicki
WojciechBilicki

Reputation: 11

write anything here...

Shouldn't you put this as a placeholder for the UITextField?

Upvotes: 0

Related Questions