3.12. Using Embedded SubexpressionsWe 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. |