Python 中的正则表达式结果过滤
我正在写一个使用正则表达式的程序,我需要对它们进行过滤,但我不知道该怎么做。我想在我的字符串中匹配所有的“red,xxxx”或“xxxx,red”这样的表达式,并把颜色“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”的结果出现,如果可能的话,我希望能聪明地跳过它们。谢谢大家的帮助!
编辑 没有引号的None也不行
3 个回答
1
我建议可以这样做:
>>> 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
2
当没有匹配的结果时,返回的不是 "None"
(带引号的字符串),而是 None
(一个特殊的对象)。虽然在条件判断中直接去掉 None
的引号是可以的,但更推荐使用 ... is None
这种写法,原因有很多。最重要的一点是,这符合风格指南(一致性通常是个好事),而且这样写在处理一些写得不太好的 __eq__
方法时不会出问题(虽然在这里不是个大问题,但为了保险起见,既然没有坏处,为什么不呢?)。
3
>>> 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
>>>
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。