我需要在之后提取这个词 @
我怎样才能做到这一点?我在想什么:
text="Hello there @bob !"
user=text[text.find("@")+1:]
print user
Run Code Online (Sandbox Code Playgroud)
输出:
bob !
Run Code Online (Sandbox Code Playgroud)
但正确的输出应该是:
bob
Run Code Online (Sandbox Code Playgroud)
Sha*_*ank 11
一个有趣的正则表达式解决方案:
>>> 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
Run Code Online (Sandbox Code Playgroud)
上面的正则表达式将在"@"字符后面拾取一个或多个字母数字字符的模式,直到找到非字母数字字符.
如果要捕获更广泛的子字符串,这是一个匹配一个或多个非空白字符的正则表达式解决方案:
>>> re.findall(r'@(\S+?)', '@Hello there @bob @!')
['Hello', 'bob', '!']
Run Code Online (Sandbox Code Playgroud)
需要注意的是,当上述正则表达式遇到像绳子@xyz@abc将捕获xyz@abc的一个结果,而不是xyz和abc独立.要解决这个问题,你可以使用否定的\s字符类同时否定@字符:
>>> re.findall(r'@([^\s@]+)', '@xyz@abc some other stuff')
['xyz', 'abc']
Run Code Online (Sandbox Code Playgroud)
这里是一个正则表达式解决方案,只有在您不需要任何数字或其他任何内容时,才能匹配一个或多个字母字符:
>>> re.findall(r'@([A-Za-z]+)', '@Hello there @bobv2.0 @!')
['Hello', 'bobv']
Run Code Online (Sandbox Code Playgroud)
所以你想要在@之后开始的单词到空格?
user=text[text.find("@")+1:].split()[0]
print(user)
bob
Run Code Online (Sandbox Code Playgroud)
编辑:@bgstech注意,如果字符串没有"@",请在之前进行检查:
if "@" in text:
user=text[text.find("@")+1:].split()[0]
else:
user="something_else_appropriate"
Run Code Online (Sandbox Code Playgroud)