how to split very long regular expression in python

python, regex

Solution

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)

Problem

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.

Original source

Related problems