A regular solution for pleasure:
>>> import re >>> re.findall(r'@(\w+)', '@Hello there @bob @!') ['Hello', 'bob'] >>> re.findall(r'@(\w+)', 'Hello there bob !') [] >>> (re.findall(r'@(\w+)', 'Hello there @bob !') or None,)[0] 'bob' >>> print (re.findall(r'@(\w+)', 'Hello there bob !') or None,)[0] None
The regular expression above will display patterns of one or more alphanumeric characters following the "@" character until a non-alphanumeric character is found.
There is a regex here to match one or more characters without spaces if you want to capture a wider range of substrings:
>>> re.findall(r'@(\S+?)', '@Hello there @bob @!') ['Hello', 'bob', '!']
Note that when the above regular expression encounters a string like @ xyz@abc , it will capture xyz@abc in one result instead of xyz and abc separately. To fix this, you can use the negative \s character class, and also negate the @ characters:
>>> re.findall(r'@([^\ s@ ]+)', '@ xyz@abc some other stuff') ['xyz', 'abc']
And here is a regular expression to match one or more characters of the alphabet only if you do not want any numbers or anything else:
>>> re.findall(r'@([A-Za-z]+)', '@Hello there @bobv2.0 @!') ['Hello', 'bobv']
source share