problem with regex

Tim Chase python.list at tim.thechases.com
Fri Jul 28 09:03:19 EDT 2006


> when I do, re.compile('[A-Za-z]:\\([^/:\*\?"<>\|])*') ...I get
> 
> sre_constants.error: unbalanced parenthesis


Because you're not using raw strings, the escapables become 
escaped, making your regexp something like

	[A-Za-z]:\([^/:\*\?"<>\|])*

(because it knows what "\\" is, but likely doesn't attribute 
significance to "\?" or "\|", and thus leaves them alone).

Thus, you have "\(" in your regexp, which is a literal 
open-paren.  But you have a ")", which is a "close a grouping" 
paren.  The error is indicating that the "close a grouping" paren 
doesn't close some previously opened paren.

General good practice shoves all this stuff in a raw string:

	r"[A-Za-z]:\\([^/:\*\?"<>\|])*"

which solves much of the headache.

-tkc







More information about the Python-list mailing list