Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

•Re: Avoiding regex backtracking

by merlyn (Sage)
on Mar 05, 2002 at 13:56 UTC ( [id://149366]=note: print w/replies, xml ) Need Help??


in reply to Avoiding regex backtracking

From the Fine Manual (perlre):
"(?>pattern)" WARNING: This extended regular expression fea- ture is considered highly experimental, and may be changed or deleted without notice. An "independent" subexpression, one which matches the substring that a standalone "pat- tern" would match if anchored at the given posi- tion, and it matches nothing other than this substring. This construct is useful for opti- mizations of what would otherwise be "eternal" matches, because it will not backtrack (see the section on "Backtracking"). It may also be use- ful in places where the "grab all you can, and do not give anything back" semantic is desirable. For example: "^(?>a*)ab" will never match, since "(?>a*)" (anchored at the beginning of string, as above) will match all characters "a" at the beginning of string, leaving no "a" for "ab" to match. In contrast, "a*ab" will match the same as "a+b", since the match of the subgroup "a*" is influenced by the following group "ab" (see the section on "Backtracking"). In particular, "a*" inside "a*ab" will match fewer characters than a standalone "a*", since this makes the tail match. An effect similar to "(?>pattern)" may be achieved by writing "(?=(pattern))\1". This matches the same substring as a standalone "a+", and the following "\1" eats the matched string; it therefore makes a zero-length assertion into an analogue of "(?>...)". (The difference between these two constructs is that the second one uses a capturing group, thus shifting ordi- nals of backreferences in the rest of a regular expression.) ...

-- Randal L. Schwartz, Perl hacker

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://149366]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-03-19 10:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found