Python regex compilation (with re.VERBOSE) doesn't work

I am trying to add comments when compiling a regular expression, but when using the re.VERBOSE flag, I no longer get matchresult.

(using Python 3.3.0)

Before:

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

Result: 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())` 

Conclusion: AttributeError: the NoneType object does not have a group attribute

+7
source share
1 answer

Whitespace is ignored (i.e. your expression is effectively DukeWann ), so you need to make sure there is 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

+8
source

All Articles