ewok
ewok

Reputation: 21443

perl, match one of multiple regular expressions

I've currently got the following code:

if ($str =~ m{^[A-Z]+-\d+$} || $str =~ m{^\d+$}){
    # do stuff
}

Is it possible to combine the 2 regular expressions into a single expression? And would that improve performance at all?

Upvotes: 2

Views: 661

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

I would use an optional non-capturing group and combine these two into

if ($str =~ m{^(?:[A-Z]+-)?\d+$}) {
    # do stuff
}

Details

  • ^ - start of string
  • (?:[A-Z]+-)? - an optional non-capturing group (? quantifier makes it match 1 or 0 times)
  • \d+ - 1 or more digits
  • $ - end of string.

Upvotes: 3

Related Questions