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

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

    From http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation:

    Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:

    re.compile("[A-Za-z_]"       # letter or underscore
               "[A-Za-z0-9_]*"   # letter, digit or underscore
              )
    

    Note that this feature is defined at the syntactical level, but implemented at compile time. The ‘+’ operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings).

提交回复
热议问题