Extract text after a specific character

I need to extract the word after @

How can i do this? What am I trying:

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

output:

 bob ! 

But the correct conclusion should be:

 bob 
+6
source share
2 answers

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'] 
+10
source

So you want the word to start after @ before space?

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

EDIT: as @bgstech's note, in cases where the line does not have a "@", do a check before:

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

Source: https://habr.com/ru/post/985830/


All Articles