liveBook · Manning

Conditional match

As explained in The Well-Grounded Rubyist, Fourth Edition

A conditional match selects between regular-expression subexpressions according to whether a specified capture was found.

A conditional match chooses between two regular-expression subexpressions according to whether a specified capture was found. Ruby supports numeric conditions such as (?(1)b|c) and named-capture conditions. section 11.5.3

Choose based on capture 1

The pattern /(a)?(?(1)b|c)/ matches "ab" because capture 1 contains "a"; it matches "c" when that optional capture is absent. It does not match "b", because the unmet condition selects the alternative "c". section 11.5.3

>> re = /(a)?(?(1)b|c)/
=> /(a)?(?(1)b|c)/
>> re.match("ab")
=> #<MatchData "ab" 1:"a">   1
>> re.match("b")
=> nil                       2
>> re.match("c")
=> #<MatchData "c" 1:nil>     3

Run the numeric conditional against all three strings and inspect the captured value in MatchData. section 11.5.3

/(?<first>a)?(?(<first>)b|c)/

Compare the numeric form with a named-capture condition using the first capture. section 11.5.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains numeric and named syntax through three match outcomes, without developing broader implementation internals.
Examples
Demonstrates /(a)?(?(1)b|c)/ against "ab", "b", and "c", then gives a named-capture equivalent.
What it assumes
Assumes familiarity with regular-expression grouping and captures; does not establish those concepts from zero.
What you can do after
Apply numeric or named conditional syntax to select a subexpression based on whether a capture matched.
How it connects
Connects conditional matches with regular expressions, captures, named captures, and subexpressions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.