find mentions in a string using regex in python

To find mentions in a string using regex in Python, you can use the re module. A mention starts with the @ symbol and is followed by a string of alphanumeric characters (with underscores). Here's the code that will find all mentions in a given string:

main.py
import re

string = "Hey @alice, have you seen @bob today?"

# define the regex pattern
pattern = r"@\w+"

# find all matches
matches = re.findall(pattern, string)

# print the matches
print(matches)
200 chars
13 lines

Output:

main.py
['@alice', '@bob']
19 chars
2 lines

Explanation:

  1. We import the re module which provides support for regular expressions in Python.
  2. We define the input string that contains mentions.
  3. We define the regex pattern, @\w+.
    • @ matches the @ symbol.
    • \w matches any alphanumeric character or underscore.
    • + indicates that there must be at least one character after the @.
  4. We use the findall() method to find all occurrences of the regex pattern in the input string.
  5. Finally, we print the matches that are found.

gistlibby LogSnag