Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split very long regular expression in python

Tags:

python

regex

i have a regular expression which is very long.

 vpa_pattern = '(VAP) ([0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}): (.*)'

My code to match group as follows:

 class ReExpr:
def __init__(self):
    self.string=None

def search(self,regexp,string):
    self.string=string
    self.rematch = re.search(regexp, self.string)
    return bool(self.rematch)

def group(self,i):
    return self.rematch.group(i)

 m = ReExpr()

 if m.search(vpa_pattern,line):
    print m.group(1)
    print m.group(2)
    print m.group(3)

I tried to make the regular expression pattern to multiple line in following ways,

vpa_pattern = '(VAP) \
    ([0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}):\
    (.*)'

Or Even i tried:

 vpa_pattern = re.compile(('(VAP) \
    ([0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}):\
    (.*)'))

But above methods are not working. For each group i have a space () after open and close parenthesis. I guess it is not picking up when i split to multiple lines.

like image 921
Naggappan Ramukannan Avatar asked Dec 25 '22 08:12

Naggappan Ramukannan


2 Answers

Look at re.X flag. It allows comments and ignores white spaces in regex.

a = re.compile(r"""\d +  # the integral part
               \.    # the decimal point
               \d *  # some fractional digits""", re.X)
like image 153
Alex Shkop Avatar answered Dec 31 '22 12:12

Alex Shkop


Python allows writing text strings in parts if enclosed in parenthesis:

>>> text = ("alfa" "beta"
... "gama")
...
>>> text
'alfabetagama'

or in your code:

text = ("alfa" "beta"
        "gama" "delta"
        "omega")
print text

will print

"alfabetagamadeltaomega"
like image 45
Jan Vlcinsky Avatar answered Dec 31 '22 14:12

Jan Vlcinsky