如何将列表元素声明为REGEX

2024-09-24 22:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我要声明正则表达式为r'塔塔.xnl.*-dev.1.0'中的list元素,它应该匹配tata.xnl.1.0-dev.1.0,如何解决这个问题?。你知道吗

productline = '8.H.5'
pl_component_dict = {'8.H.5': [r'tata.xnl.*-dev.1.0','tan.xnl.1.0-dev.1.0'],
                     '8.H.7':['']
                     }
component_branch = "tata.xnl.1.0-dev.1.0"
if component_branch in pl_component_dict[productline] :
    print "PASS"
else:
    print "ERROR:Gerrit on incorrect component"

你知道吗错误:-你知道吗

ERROR:Gerrit on incorrect component

Tags: branch声明元素onerrordictlistcomponent
3条回答

这里有一种使用^{}的方法:

import re

class ReList:
    def __init__(self, thinglist):
        self.list = thinglist
    def contains(self, thing):
        re_list = map( lambda x: re.search( x, thing) , self.list)
        if any( re_list):
            return True
        else:
            return False

my_relist = ReList( ['thing0', 'thing[12]'] )

my_relist.contains( 'thing0')
# True
my_relist.contains( 'thing2')
# True
my_relist.contains( 'thing3')
# False

any语句之所以有效,是因为re.search要么返回布尔值为True的^{},要么返回None。你知道吗

在字符串前面加r并不能使它成为正则表达式,而是使它成为raw string literal。你知道吗

您需要使用re.compile()将它编译成正则表达式。你知道吗

import re
...
for component in pl_component_dict[productline]:
    if re.compile(component).match(component_branch):
        print "PASS"
        break
else: # note that this becomes a for-else, not an if-else clause
    print "ERROR:Gerrit on incorrect component"

这个for else循环处理在pl_component_dict[productline]中有一个列表的事件,就像在本例中一样。你知道吗

使编译的字典值re与您的字符串匹配:

import re

productline = '8.H.5'

pattern = re.compile(r'tata.xnl.\d\.\d-dev.1.0')
pl_component_dict = {'8.H.5': pattern}

component_branch = "tata.xnl.1.0-dev.1.0"

if pl_component_dict[productline].match(component_branch):
    print "PASS"
else:
    print "ERROR:Gerrit on incorrect component"

相关问题 更多 >