简体   繁体   中英

Break python regular expression with escape into multiple lines

I have a python beginner's question. How would one break this line into multiple lines?

SET_CMD = re.compile (r'boot +set-cmd +-s +command\=(?P<pw>.*?)$')

I don't want to do this because pep8 complains.

SET_CMD = re.compile\
    (r'boot +set-cmd +-s +command\=(?P<pw>.*?)$')

Thanks, Mat

Do something like this:

SET_CMD = re.compile (r'boot +set-cmd +-s'
                      r' +command\=(?P<pw>.*?)$')

There are two key facts here:

  • being inside of parentheses provides implicit line continuation
  • consecutive strings are automatically concatenated

Instead of breaking before the parantheses, you could use the regex verbosity flag to split the expression in multiple lines. Additionally you can include comments, which might come handy for complicated expressions.

For your example:

SET_CMD = re.compile(r'''boot\s        # Comment
                         +set-cmd\s    # ...
                         +-s\s
                         +command
                         \=(?P<pw>.*?)$')''', re.VERBOSE)

Note that I inserted some \\s to match whitespaces, since re.VERBOSE ignores the whitespaces and linebreaks in the expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM