Python Forum
Regex on more than one line ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Regex on more than one line ? (/thread-24945.html)



Regex on more than one line ? - JohnnyCoffee - Mar-11-2020

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 ?


RE: Regex on more than one line ? - micseydel - Mar-11-2020

Try implicit string concatenation:
var = re.match(
  r"my.."     # comment here
  r"........" # comment here
  r"........"
  r"...............................................................regex too long",
  string)



RE: Regex on more than one line ? - snippsat - Mar-12-2020

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]']



RE: Regex on more than one line ? - JohnnyCoffee - Mar-12-2020

(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.