如何在遇到某些特殊符号后切断字符串

时间:2014-10-24 16:43:17

标签: python django

我有message = 'This is a private post. Cc: @me, @you.and @others,too. I @hope>this is okay'

我在迭代startswith('@')之后提取了message.split(' ')符号的单词。

这产生了mentions = ['@me', '@you.and', '@others,too', '@hope>this'],这不是我想要的。

所需的结果是mentions = ['@me', '@you', '@others', '@hope']

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

>>> import re
>>> x = 'This is a private post. Cc: @me, @you.and @others,too. I @hope>this is okay'
>>> [re.search(r'(@\w+)', z).groups()[0] for z in x.split() if z.startswith('@')]
['@me', '@you', '@others', '@hope']

答案 1 :(得分:0)

>>> import re
>>> s = "This is a private post. Cc: @me, @you.and @others,too. I @hope>this is okay"
>>> re.findall(r"(@\w+)\b", s)
['@me', '@you', '@others', '@hope']