shemp has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to use a negative lookahead assertion in a regex, and i don't understand what's going on with 1 form of the regex. I'm parsing snail mail addresses, particularly for horrible beasts like "456 4 1/2 MILE RD". For this address, the street number is 456, and the street name is "4 1/2 MILE RD" (four and one-half mile road). If the word "MILE" is not there, then the 1/2 is generally treated as a unit number. (im not going to go into the complete details) Suffice to say that i'm looking to detect a 1/2, followed by something other that MILE. So, a first attempt at a regex is like this:
If i change the regex so the whitespace is "\s+", then the match evaluates to false, as i expected. But both * and + are greedy, so all whitespace should be sucked up either way, but with *, it should be optional. And i will have cases where there isnt any whitespace.
I used the following, which works like i want it to:
BTW: this is a reduced case, yes we have other boundary conditions, i'm just perplexed about the regex behaviour
If $address = "4 1/2 MILE RD" this evaluates to true, but i dont see why. There is a "1/2", followed by whitespace. Then there is "MILE", which evaluates to false because of the negative lookahead.if ($address =~ /(1\/2)\s*(?!MILE)/i) { ...
If i change the regex so the whitespace is "\s+", then the match evaluates to false, as i expected. But both * and + are greedy, so all whitespace should be sucked up either way, but with *, it should be optional. And i will have cases where there isnt any whitespace.
I used the following, which works like i want it to:
Myself and another programmer have absolutely no idea why the first regex doesnt work as planned, so any insight would be greatly appreciated.if ($address =~ /(1\/2)(?!\s*MILE)/i) { ...
BTW: this is a reduced case, yes we have other boundary conditions, i'm just perplexed about the regex behaviour
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: regex negative lookahead behaviour
by broquaint (Abbot) on Jul 18, 2003 at 17:14 UTC | |
Re: regex negative lookahead behaviour
by BrowserUk (Patriarch) on Jul 18, 2003 at 17:08 UTC | |
by pijll (Beadle) on Jul 19, 2003 at 11:49 UTC | |
Re: regex negative lookahead behaviour
by sauoq (Abbot) on Jul 18, 2003 at 17:15 UTC | |
Re: regex negative lookahead behaviour
by flounder99 (Friar) on Jul 18, 2003 at 18:51 UTC | |
by shemp (Deacon) on Jul 18, 2003 at 19:34 UTC | |
Re: regex negative lookahead behaviour
by dws (Chancellor) on Jul 18, 2003 at 19:34 UTC | |
by BazB (Priest) on Jul 20, 2003 at 11:19 UTC | |
Re: regex negative lookahead behaviour
by jonadab (Parson) on Jul 19, 2003 at 13:46 UTC | |
Re: regex negative lookahead behaviour
by princepawn (Parson) on Jul 18, 2003 at 18:10 UTC | |
by sauoq (Abbot) on Jul 18, 2003 at 18:59 UTC |
Back to
Seekers of Perl Wisdom