我有一个字符串:
This is @lame在这里,我想提取lame。但这里有个问题,上面的字符串可能是
This is lameThis is @lame but that is @not在这里,我摘录了lame和not
因此,我在每种情况下期望的输出是:
[lame]
[]
[lame,not]如何在python中以健壮的方式提取这些内容?
发布于 2013-05-08 01:46:31
使用re.findall()查找多个模式;在本例中,任何以@开头的模式都由单词字符组成:
re.findall(r'(?<=@)\w+', inputtext)(?<=..)构造是一个正向回看断言;只有当当前位置前面有一个@字符时,它才匹配。因此,上面的模式匹配1个或多个单词字符( \w字符类),前提是这些字符前面有一个@符号。
演示:
>>> import re
>>> re.findall(r'(?<=@)\w+', 'This is @lame')
['lame']
>>> re.findall(r'(?<=@)\w+', 'This is lame')
[]
>>> re.findall(r'(?<=@)\w+', 'This is @lame but that is @not')
['lame', 'not']如果您计划重用该模式,请首先编译表达式,然后在编译后的正则表达式对象上使用.findall() method:
at_words = re.compile(r'(?<=@)\w+')
at_words.findall(inputtext)这为您在每次调用.findall()时节省了一次缓存查找。
发布于 2013-05-08 01:46:58
这将给出您请求的输出:
import re
regex = re.compile(r'(?<=@)\w+')
print regex.findall('This is @lame')
print regex.findall('This is lame')
print regex.findall('This is @lame but that is @not')发布于 2013-05-08 01:48:03
你应该使用re lib,下面是一个例子:
import re
test case = "This is @lame but that is @not"
regular = re.compile("@[\w]*")
lst= regular.findall(test case)https://stackoverflow.com/questions/16425296
复制相似问题