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'
The VERBOSE flag of the regex package allows the user to write regular expressions that can look nicer and are more readable. This flag does that by allowing the users to visually separate the logical sections of the pattern and add more comments.
Python's re. compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re. match() or re.search() .
VERBOSE. This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments.
Python has a module named re to work with RegEx. Here's an example: import re pattern = '^a...s$' test_string = 'abyss' result = re. match(pattern, test_string) if result: print("Search successful.") else: print("Search unsuccessful.")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With