Is there something in regex to match (conditionally) only if it exists ?
e.g.
the string maybe
question_1
or only
question
In case of the former, it should match the integer in the end, but as in the case of the latter, it should leave it.
If the if part evaluates to true, then the regex engine will attempt to match the then part. Otherwise, the else part is attempted instead. The syntax consists of a pair of parentheses. The opening bracket must be followed by a question mark, immediately followed by the if part, immediately followed by the then part.
In order to match a line that does not contain something, use negative lookahead (described in Recipe 2.16). Notice that in this regular expression, a negative lookahead and a dot are repeated together using a noncapturing group.
The ?
is the 0-1 quantifier in Regexes. \d?
means 0 or 1 digit. The *
is the 0-infinite quantifier. \d*
means 0 or more digits. Is it what you want?
(additionally the +
is the 1 or more quantifier, and not quantifier means exactly 1)
To elaborate on what you asked, I would say
question(_\d+)?
question
followed by an optional (_
AND 1 or more digits)
Where the brackets are only to group the sub expression (they are "mathematical" brackets)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With