Alex Rivera | Logout

RegEx match if present

Asked 2011-10-08T12:19:45.100
13

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.

Edit
Report

3 Answers

3

Don't quite understand the question. Do you just want to extract the number?

question_(\d+)
answered 2011-10-08T12:26:05.487
1

in perl you could do something like:

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

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

answered 2011-10-08T12:25:48.890
1

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

question(?:_\d)?

answered 2011-10-08T12:27:22.603

Your Answer