RegEx compliance, if present

Is there anything in the regular expression for matching (conditionally) only if it exists?

eg.

string can be

question_1 

or only

 question 

In the case of the former, it must correspond to an integer at the end, but, as in the case of the latter, it must leave it.

+4
source share
5 answers

? is the 0-1 quantifier in Regexes. \d? means 0 or 1 digit. * - 0-infinite quantifier. \d* means 0 or more digits. Is this what you want? (in addition, + is 1 or more quantifiers, and not a quantifier means exactly 1)

To clarify what you asked, I would say

 question(_\d+)? 

question and then optional ( _ AND 1 or more digits)

In cases where the brackets are only for grouping subexpressions (they are "mathematical" brackets)

+5
source

I did not quite understand the question. Do you just want to extract the number?

 question_(\d+) 
+2
source

in perl you can do something like:

 my $string = 'question_1'; my $question_number = $string =~ /question_(\d+)/i; 

now $question_number will contain int if it matches and will be undef if it doesn't

+1
source

If you want to extract the question(?:_?)(\d)?

+1
source

If underscore and number are optional, try something like this:

question(?:_\d)?

0
source

All Articles