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

前端 未结 6 1868
日久生厌
日久生厌 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:32

    Either use string concatenation like in the answer of naeg or use re.VERBOSE/re.X, but be careful this option will ignore whitespace and comments. You have some spaces in your regex, so those would be ignored and you need to either escape them or use \s

    So e.g.

    test = re.compile("""(?P.+):\d+: # some comment
        \s+warning:\s+Member\s+(?P.+) #another comment
        \s+\((?P%s)\)\ of\ (class|group|namespace)\s+
        (?P.+)\s+is\ not\ documented""" % (self.__MEMBER_TYPES), re.IGNORECASE | re.X)
    

提交回复
热议问题