【发布时间】:2014-09-14 17:28:09
【问题描述】:
当用户在字符串中写入@ 表达式时,我想解析所有用户名。
例子:
I want to tell @susan and @rick that I love you all.
我想从字符串中得到['susan', 'rick'],解析表达式怎么写?
【问题讨论】:
当用户在字符串中写入@ 表达式时,我想解析所有用户名。
例子:
I want to tell @susan and @rick that I love you all.
我想从字符串中得到['susan', 'rick'],解析表达式怎么写?
【问题讨论】:
为此写一个表达式并不难。
>>> 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']
【讨论】:
>>> 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']
>>>
【讨论】:
import re
# input string
myStr = "tell @susan and @rick that"
# match
names = re.findall(r"@(\w+)", myStr)
【讨论】:
使用正则表达式的答案也很有效。对于多样性,这里是一个列表比较。
>>> 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']
【讨论】:
@ 之前的部分。