Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex compile (with re.VERBOSE) not working

Tags:

python

regex

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'

like image 270
bfloriang Avatar asked Dec 07 '12 10:12

bfloriang


People also ask

What is verbose RegEx?

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.

What is RegEx re compile?

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

What is Python verbose?

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.

How do you use re in Python?

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.")


1 Answers

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

like image 183
Jon Clements Avatar answered Oct 26 '22 15:10

Jon Clements