Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I determine which regex in an either or statement matches my string?

Tags:

regex

perl

For this statement:

if ($SDescription =~ m/$sdescription_1/gi or $SDescription =~ m/$sdescription_2/gi){
#...
}

Besides printing $SDescription to compare it manually, is it possible to tell which $SDescription matched: $sdescription_1 or $sdescription_2?

like image 238
user0 Avatar asked Dec 25 '22 13:12

user0


2 Answers

In scalar context, the =~ operator returns the number of matches. Without the /g modifier, the number of matches is either 0 or 1, so you could do something like

$match_val = ($SDescription =~ m/$sdescription_1/i)
         + 2 * ($SDescription =~ m/$sdescription_2/i);
if ($match_val) {

    if ($match_val == 1) { ... }  # matched first regex
    if ($match_val == 2) { ... }  # matched second regex
    if ($match_val == 3) { ... }  # matched both regex

}
like image 124
mob Avatar answered Dec 28 '22 01:12

mob


Is there a reason why you don't want to write something like this? (The /g modifier is superflous unless you are using the \G anchor in a later match: a pattern either matches or it doesn't.)

if ($SDescription =~ /$sdescription_1/i) {
  # Do stuff for first pattern
}
elsif ($SDescription =~ /$sdescription_2/i) {
  # Do stuff for second pattern
}
like image 24
Borodin Avatar answered Dec 28 '22 01:12

Borodin