in reply to Get the last occurence of a pattern
Doesn't work, please ignore
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Get the last occurence of a pattern
by Corion (Patriarch) on Jun 14, 2007 at 11:14 UTC | |
Not really:
prints EF, because the pattern matches at the earliest possible location. A possible fix would be to prepend a greedy .* which pushes the start of the following pattern as far to the right as possible:
The trailing .*?$ is superfluous, because the pattern will either match or not, regardless of the anchor. | [reply] [d/l] [select] |
by tye (Sage) on Jun 14, 2007 at 17:19 UTC | |
Note that my two solutions aren't identical. Given your pattern of / \w\w /, you'd want to use /.*($PATTERN)/ not ( /($PATTERN)/g )[-1] because the second case wouldn't DWIM with "overlapping matches":
You could "fix" my second technique by switching the pattern to /(?<= )\w\w(?= )/ so that matches never overlap. But that doesn't make the second choice "better". There are also patterns where the second technique won't DWIM but the first technique will. In particular, patterns that need to be greedy need the first technique or else they won't be greedy:
Which begs one to ask what technique will get the "last match" and DWIM in the face of a greedy pattern with overlapping matches.
This illustrates an important point about regular expressions. They prefer to be greedy but more than that they prefer to match left-most (that is, to match earlier in the string rather than further to the right in the string). That is why texts on regexes say "greedy" as "left-most longest" (and not "longest left-most"). So I've hypothesized a case where we first want the match to end as far right as possible and second want the match to start as far left as possible. One way to get this from the regex engine is to use a "sexeger" (reverse the string and compose the regex backward), a technique coined by japhy:
You could also get it with more "brute force":
- tye | [reply] [d/l] [select] |