problem with regex

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


>>>> regex = r'[A-Za-z]:\\([^/:\*\?"<>\|])*'
>>>> p = re.compile(regex)
>>>> p.match('c:\\test')
> <_sre.SRE_Match object at 0x009D77E0>
>>>> p.match('c:\\test?:/')
> <_sre.SRE_Match object at 0x009D7720>
> 
> the last example shouldnt give a match

Ah, but it should, because it *does* match.

 >>> m = p.match('c:\\test?:/')
 >>> m.group(0)
'c:\\test'
 >>> # add a "$" at the end to anchor it
 >>> # to the end of the line
 >>> regex = r'[A-Za-z]:\\([^/:\*\?"<>\|])*$'
 >>> p = re.compile(regex)
 >>> m = p.match('c:\\test?:/')
 >>> m

By adding the "$" to ensure that you're matching the whole string 
passed to match() and not just as much as possible given the 
regexp, you solve the problem you describe.

-tkc






More information about the Python-list mailing list