简体   繁体   中英

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

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']

So you want the word starting after @ up to a whitespace?

user=text[text.find("@")+1:].split()[0]
print(user)
bob

EDIT: as @bgstech note, in cases where the string does not have a "@", make a check before:

if "@" in text:
    user=text[text.find("@")+1:].split()[0]
else:
    user="something_else_appropriate"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM