当用户在字符串中写入@
表达式时,我想解析所有用户名。
示例:
I want to tell @susan and @rick that I love you all.
我想从字符串中获取['susan', 'rick']
,如何编写解析表达式?
答案 0 :(得分:4)
为此编写表达式并不是很难。
>>> import re
>>> re.findall(r'@(\S+)', ' I want to tell @susan and @rick that I love you all')
['susan', 'rick']
或使用匹配任何单词字符的\w
。
>>> re.findall(r'@(\w+)', ' I want to tell @susan and @rick that I love you all')
['susan', 'rick']
答案 1 :(得分:1)
>>> import re
>>> s = "I want to tell @susan and @rick that I love you all."
>>> m = re.findall(r'@[a-z]+', s)
>>> m
['@susan', '@rick']
>>>
答案 2 :(得分:1)
import re
# input string
myStr = "tell @susan and @rick that"
# match
names = re.findall(r"@(\w+)", myStr)
答案 3 :(得分:0)
使用正则表达式的答案也很有效。对于多样性,这里有一个列表comp。
>>> s = 'I want to tell @susan and @rick that I love you all.'
>>> [i.strip('@') for i in s.split() if '@' in i]
['susan', 'rick']