Boy do REs ever suck sometimes...

Tim Peters tim.one at home.com
Fri Oct 5 08:58:14 CEST 2001


[Ignacio Vazquez-Abrams]
> Here's the problem I'm having with REs. When I use an RE like 
> '^[0-9]+$' it matches both '123' and '123\n'. How can I get it to not
> match the string with the newline?

A straightforward way:

>>> import re
>>> pat = re.compile(r'\d+\Z')
>>> pat.match('123')
<SRE_Match object at 0x007AC8C0>
>>> pat.match('123\n')
>>>

A sicker way:

>>> pat = re.compile(r'\d+(?!\n)$')
>>> pat.match('123')
<SRE_Match object at 0x007AB6F0>
>>> pat.match('123\n')
>>>

you-can't-truly-give-up-regexps-before-mastering-them<wink>-ly y'rs  - tim





More information about the Python-list mailing list