How to split long regular expression rules to multiple lines in Python

前端 未结 6 1880
日久生厌
日久生厌 2020-11-30 02:58

Is this actually doable? I have some very long regex pattern rules that are hard to understand because they don\'t fit into the screen at once. Example:

test         


        
6条回答
  •  误落风尘
    2020-11-30 03:52

    Just for completeness, the missing answer here is using the re.X or re.VERBOSE flag, which the OP eventually pointed out. Besides saving quotes, this method is also portable on other regex implementations such as Perl.

    From https://docs.python.org/2/library/re.html#re.X:

    re.X
    re.VERBOSE
    

    This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class or when preceded by an unescaped backslash. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored.

    This means that the two following regular expression objects that match a decimal number are functionally equal:

    a = re.compile(r"""\d +  # the integral part
                       \.    # the decimal point
                       \d *  # some fractional digits""", re.X)
    

     

    b = re.compile(r"\d+\.\d*")
    

提交回复
热议问题