Farbour
Farbour

Reputation: 171

How do I strip hash tags from a tweet and return them as an array?

I need to strip hashtags from a tweet and return those hash tags as an array.

I know this is possible with the proper regex but I can't seem to find the right regex to use.

Upvotes: 4

Views: 905

Answers (2)

Nakilon
Nakilon

Reputation: 35112

"#qwe rty#asd #fgh".scan(/(?:^|\s)(#\S+)/).flatten

or

"#qwe rty#asd #fgh".split.grep /^#./

Upvotes: 2

Roadmaster
Roadmaster

Reputation: 5357

hashtag_array = tweet.split.find_all{|word| /^#.+/.match word}

Split the string containing the tweet (by default split splits on whitespace). The resulting array contains all the words in the tweet. find_all returns an array with elements in the original array for which the given block returns true. So in the block we check for words beginning with the hash (#).

Documentation on the split method is here, find_all is here.

Upvotes: 10

Related Questions