find hashtags in a string using regex in python

To find hashtags in a string using regex in Python, we can use the re module. Here's an example code snippet:

import re

string = "Hello #world! This is a #test string with #hashtags"
hashtags = re.findall(r"#\w+", string)
print(hashtags)
129 chars
6 lines

Output:

['#world', '#test', '#hashtags']
33 chars
2 lines

Here we firstly imported the re module. Then define a string that contains hashtags ("#"). Then, used the re.findall() method. This method returns all non-overlapping matches of the regular expression (r"#\w+") in the string. The regular expression "#\w+" matches any word that starts with a hashtag (#) character. Finally, we print the list of hashtags.

This code snippet can also be further customized according to specific needs.

gistlibby LogSnag