Skip to main content
 首页 » 编程设计

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

2025年05月04日24freeliver54

我正在开发一个带有正则表达式的程序,我必须过滤它们,但我不知道如何过滤。我想匹配字符串中的每个 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 不带引号也不起作用

请您参考如下方法:

>>> 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 
>>>