Section 3.13. Ruby and Oniguruma

3.12. Using Embedded Subexpressions

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 possessivethat 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.

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: