1

I have multiple patterns to check against. Say hello and bye, but will be many more, so I chose to use re.compile() to store them and then being able to check this regex:

import re

mypatt = re.compile(r'(hello|bye)', re.IGNORECASE)
url = ["bye bye", "hello how are you", "i am fine", "ok byeee"]
for u in url:
    if mypatt.search(u):
        print "yes --> %s" %(u)

Upon running this code I get the desired output:

yes --> bye bye
yes --> hello how are you
yes --> ok byeee

However, since there are multiple patterns I would like to write one per line, with something like:

mypatt = re.compile(r'(\
    hello|\
    bye\
    )', re.IGNORECASE)

However this does not work and I cannot understand why. What is the way to write such statement, writing every pattern in a different line?

5
  • 3
    You need the re.VERBOSE flag to ignore unescaped whitespace, I think. Commented Dec 30, 2015 at 15:39
  • @jonrsharpe good one! re.compile(r"""( ... )""", re.IGNORECASE |re.VERBOSE) made it. Feel free to post it as an answer if you want. Commented Dec 30, 2015 at 15:41
  • 1
    Using the verbose flag even allows one to enter comments per line. Commented Dec 30, 2015 at 15:44
  • @Evert interesting, thanks. I just found a nice example in the re.VERBOSE reference. Commented Dec 30, 2015 at 15:45
  • Yup, the reference works well here. I see I was mistaken about quoting each line though. Commented Dec 30, 2015 at 15:46

1 Answer 1

3

You're creating a pattern that includes the whitespace at the start of each line. To avoid this, either:

  1. Use textwrap.dedent, which removes common leading whitespace from each line in a multiline string; or

  2. Add the re.VERBOSE (or re.X) flag to ignore unescaped whitespace and allow the addition of inline comments.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.