Boy do REs ever suck sometimes...

Ignacio Vazquez-Abrams ignacio at openservices.net
Fri Oct 5 03:08:44 EDT 2001


On Fri, 5 Oct 2001, Tim Peters wrote:

> [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')
> >>>

Ah, beautiful; just what I was looking for. Thank you.

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

Well, it works, but the other way is definitely more explicit.

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

Not giving up, just figuring them out ;)

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>





More information about the Python-list mailing list