9

I'm trying to put comments in when compiling a regex but when using the re.VERBOSE flag I get no matchresult anymore.

(using Python 3.3.0)

Before:

regex = re.compile(r"Duke wann", re.IGNORECASE)
print(regex.search("He is called: Duke WAnn.").group())

Output: Duke WAnn

After:

regex = re.compile(r'''
Duke # First name 
Wann #Last Name
''', re.VERBOSE | re.IGNORECASE)

print(regex.search("He is called: Duke WAnn.").group())`

Output: AttributeError: 'NoneType' object has no attribute 'group'

bfloriang
  • 516
  • 1
  • 7
  • 11
  • Actually that's the wrong syntax for a raw multiline string: `r'''this is wrong'''` . The right syntax must use r with double-quotes: `r"""this is right"""`. See [How to correctly write a raw multiline string in Python?](https://stackoverflow.com/questions/46003452/how-to-correctly-write-a-raw-multiline-string-in-python) – smci Nov 17 '17 at 00:56

1 Answers1

13

Whitespaces are ignored (ie, your expression is effectively DukeWann), so you need to make sure there's a space there:

regex = re.compile(r'''
Duke[ ] # First name followed by a space
Wann #Last Name
''', re.VERBOSE | re.IGNORECASE)

See http://docs.python.org/2/library/re.html#re.VERBOSE

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • Does this necessitate that all literal spaces be substituted with `[ ]` in the regex? This seems to be the case as far as I can tell. – Brad Solomon Nov 08 '17 at 17:33
  • @Brad yes. They need to be explicitly stated as per one of the ways the docs mention – Jon Clements Nov 08 '17 at 17:38
  • Actually that's the wrong syntax for a raw multiline string: `r'''this is wrong'''` . The right syntax must use r with double-quotes: `r"""this is right"""`. See [How to correctly write a raw multiline string in Python?](https://stackoverflow.com/questions/46003452/how-to-correctly-write-a-raw-multiline-string-in-python) – smci Nov 17 '17 at 00:56
  • 3
    @smci they're the same thing as far as the grammar is concerned so while one could argue using quotes is more PEP8 like I'm not sure exactly why you're asserting one is correct and the other isn't...? – Jon Clements Nov 17 '17 at 02:26