Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx match if present

Tags:

regex

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.

like image 390
yolo Avatar asked Oct 08 '11 12:10

yolo


People also ask

Can we use regex in if condition?

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.

How do you say does not contain in regex?

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.


1 Answers

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)

like image 176
xanatos Avatar answered Nov 06 '22 15:11

xanatos