I need to detect @username
mentions within a message, but NOT if it is in the form of @username[user_id]
. I have a regex that can match the @username
part, but am struggling to negate the match if it is followed by \[\d\]
.
import re
username_regex = re.compile(r'@([\w.@-]+[\w])')
usernames = username_regex.findall("Hello @kevin") # correctly finds kevin
usernames = username_regex.findall("Hello @kevin.") # correctly finds kevin
usernames = username_regex.findall("Hello @kevin[1].") # shouldn't find kevin but does
The regex allows for usernames that contain @
, .
and -
, but need to end with a \w
character ([a-zA-Z0-9_]
). How can I extend the regex so that it fails if the username is followed by the userid in the [1]
form?
I tried @([\w.@-]+[\w])(?!\[\d+\])
but then it matches kevi
I'm using Python 3.10.