Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract text after specific character

I need to extract the word after the @

How can I do that? What I am trying:

text="Hello there @bob !"
user=text[text.find("@")+1:]
print user

output:

bob !

But the correct output should be:

bob
like image 834
user2990084 Avatar asked Apr 24 '15 00:04

user2990084


1 Answers

A regex solution for fun:

>>> 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 regex above will pick up patterns of one or more alphanumeric characters following an '@' character until a non-alphanumeric character is found.

Here's a regex solution to match one or more non-whitespace characters if you want to capture a broader range of substrings:

>>> re.findall(r'@(\S+?)', '@Hello there @bob @!')
['Hello', 'bob', '!']

Note that when the above regex encounters a string like @xyz@abc it will capture xyz@abc in one result instead of xyz and abc separately. To fix that, you can use the negated \s character class while also negating @ characters:

>>> re.findall(r'@([^\s@]+)', '@xyz@abc some other stuff')
['xyz', 'abc']

And here's a regex solution to match one or more alphabet characters only in case you don't want any numbers or anything else:

>>> re.findall(r'@([A-Za-z]+)', '@Hello there @bobv2.0 @!')
['Hello', 'bobv']
like image 164
Shashank Avatar answered Sep 21 '22 15:09

Shashank