in reply to Probably silly regex question / not so silly regex question
The answer is Yes, those regexes absolutely match different things.> Will a regex of the form .*c ever match differently > from [^c]*c, and if not, why doesn't the regex parser > optimize it to the later form? What if the first was .*?c
Take the string "abcabc". 1 will print "abcabc" because it's greedy. 2 will print "abc" because it is looking for anything except a c, followed by a c. 3 will also print "abc" because it's non-greedy; it takes the first match instead of the longest.1. m/(.*c)/ && print $1; 2. m/([^c]*c)/ && print $1; 3. m/(.*?c)/ && print $1;
How they match is also different. 1 will match everything until the end of the string, then backtrack, one character at a time, until the last character in the match is a "c" (a summarized explanation). 2 will only gobble up until it finds a c, because the c won't satisfy [^c]; then it matches the c. No backtracking. The non-greedy version (3) will match zero characters, and then look for a c; then match 1 character, and then look for a c; then match match 2 characters, and look for a c; and so on.
This difference in how the matching is done has a big influence on performance. Since .* will always gobble up the whole string, and then backtrack, if you have a Really Long String which starts with "abc", it'll take a Really Long Time (relatively) for pattern 1 to match, compared to pattern 2 or pattern 3.
As for your first question... I'm not entirely sure why it's not working. I'll try it out and update if I come up with anything.
Alan
Update: I'm not willing to say that Under All Circumstances, patterns 2 and 3 above will match the same thing. I can't think of a counterexample off the top of my head, but that doesn't mean one doesn't exist. I'm also not willing to say that one is faster than the other without benchmarking. For all I Really Know, they could match the same thing, and perl could already be optimizing one into the other for the sake of performance. But, you're right, it does certainly look like they'll both always match the same thing. Not necessarily, if part of a larger regex, though.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: RE: Probably silly regex question / not so silly regex question
by theorbtwo (Prior) on Aug 01, 2000 at 23:24 UTC | |
by jlistf (Monk) on Aug 01, 2000 at 23:34 UTC | |
by Anonymous Monk on Aug 02, 2000 at 01:13 UTC |