October 2006
Intermediate to advanced
888 pages
16h 55m
English
We can use the ?> notation to specify subexpressions in a regex:
re = /(?>abc)(?>def)/ # Same as /abcdef/
re.match("abcdef").to_a # ["abcdef"]Notice that the subexpressions themselves don’t imply grouping. We can turn them into capturing groups with additional parentheses, of course.
Note that this notation is possessive—that is, it is greedy, and it does not allow backtracking into the subexpression.
str = "abccccdef" re1 = /(abc*)cdef/ re2 = /(?>abc*)cdef/ re1 =~ str # 0 re2 =~ str # nil re1.match(str).to_a # ["abccccdef", "abccc"] re2.match(str).to_a # []
In the preceding example, re2’s subexpression abc* consumes all the instances of the letter c, and it (possessively) won’t give them back to allow backtracking. ...
Read now
Unlock full access