Python Forum

Full Version: Regex on more than one line ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a regular expression that is long how do I organize the regex by skipping lines just so it doesn't get too long, ex :

var = re.match(r"my.................................................................................regex too long", string)
how can i continue writing the regex by skipping line ?
Try implicit string concatenation:
var = re.match(
  r"my.."     # comment here
  r"........" # comment here
  r"........"
  r"...............................................................regex too long",
  string)
There is what re.VERBOSE is made for splitting up long regex and eg adding comments.
import re

email = re.compile(r"""
    [\w.]+        # match any alphanumeric character or a period
    @             # match the character literally
    \w+\.[a-z]{3} # Any character followed by period and exactly three lower-case letters""", re.VERBOSE)
print(email.findall('[email protected] [email protected]')
Output:
['[email protected]']
The same as.
import re

email = re.compile(r'[\w.]+@\w+\.[a-z]{3}')
print(email.findall('[email protected] [email protected]'))
Output:
['[email protected]']
(Mar-11-2020, 11:51 PM)micseydel Wrote: [ -> ]Try implicit string concatenation:
var = re.match(
  r"my.."     # comment here
  r"........" # comment here
  r"........"
  r"...............................................................regex too long",
  string)
Thank.