1

I want to declare a regex as r'tata.xnl.*-dev.1.0' in the list element and it should match tata.xnl.1.0-dev.1.0,how to solve this problem?.

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

ERROR:Gerrit on incorrect component
  • What `tata.xnl.1.0-dev.1.0` should it match? Do you expect the regex to match or the `component_branch in..` to match. If it's the regex, how do you expect it to match anything if you don't _use_ the pattern with one of the `re` methods? – martineau Jul 08 '16 at 22:03

3 Answers3

0

Make the dictionary value(s) compiled re that can match your string:

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"
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Prepending r to a string does not make it a regular expression - it makes it a raw string literal.

You need to compile it into a regular expression using 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"

This for-else loop takes care of the event where you have a list in pl_component_dict[productline] as you do in this case.

Community
  • 1
  • 1
Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
0

Here is one way using re.search:

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

The any statement works because re.search either returns an re.MatchObject with a boolean value of True, or else it returns None.

dermen
  • 5,252
  • 4
  • 23
  • 34