12

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.

3
  • 2
    What does "leave it" mean? Do you want to match either string regardless of whether or not there is an underscore and a number at the end? Commented Oct 8, 2011 at 12:26
  • 1
    This question denotes a null knowledge of Regexes. Not even zero. Null. SO isn't a tutorial. When you post here you should know at least the basics of the argument you are asking about.
    – xanatos
    Commented Oct 8, 2011 at 12:33
  • Are you trying to say, If there is an underscore, a number must be followed, otherwise there should be no underscore at the end ?
    – Anwar
    Commented Jun 5, 2016 at 7:59

5 Answers 5

13

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)

3

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

question_(\d+)
3

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

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

1

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

question(?:_\d)?

1
  • He tried to say, if there is an underscore, then a number should be present. otherwise, only the "question" without no ending _
    – Anwar
    Commented Jun 5, 2016 at 7:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.