Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

ruby

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.

like image 259
Farbour Avatar asked Dec 16 '22 19:12

Farbour


1 Answers

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.

like image 64
Roadmaster Avatar answered May 30 '23 11:05

Roadmaster