python中的正则表达式结果过滤器



我正在研究一个正则表达式程序,我必须过滤它们,但我不知道如何。我想匹配字符串中的每个红色xxxx或xxxx红色表达式,并将xxxx颜色放入一个组中。下面是我的代码:

string = "blue,red   red,yellow   blue,yellow   red,green   purple red, ..."
regex = re.compile('(?:red,(?P<redfirst>w+)|(?P<othercolorfirst>w+),red)')

然后我写:

for match in regex.finditer(string):
    if match.group('redfirst')!= "None":
        print(match.group("redfirst"))

但我仍然得到这样的打印:

None
yellow
green
None

我不希望'None'结果出现,如果可能的话,我必须以一种聪明的方式跳过它们。谢谢你的帮助!

EDIT不加引号也不行

>>> import re
>>> regex = re.compile('(?:red,(?P<redfirst>w+)|(?P<othercolorfirst>w+),red)')
>>> string = "blue,red   red,yellow   blue,yellow   red,green   purple red, ..."
>>> for matches in regex.finditer(string):
...     if matches.group('redfirst'):
...         print matches.group('redfirst')
...
yellow
green
>>>

没有匹配的结果不是"None"(字符串),而是None(单例对象)。虽然在你的条件下简单地去掉None周围的引号是有效的,但出于许多原因,更倾向于使用... is None,最重要的是它在样式指南中(嘿,一致性获胜-通常),并且它不会在写得不好的__eq__上崩溃(这里不是问题,无论如何更多的是偏执,但既然没有缺点,为什么不呢?)。

我建议这样做:

>>> redfirst, othercolorfirst = zip(*(m.groups() for m in regex.finditer(string)))
>>> redfirst
(None, 'yellow', 'green')
>>> othercolorfirst
('blue', None, None)
>>> filter(None, redfirst)
('yellow', 'green')
>>> filter(None, othercolorfirst)
('blue',)
>>> print "n".join(filter(None, redfirst))
yellow
green

最新更新