Can I determine which regular expression in any of the statements matches my string?

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 indicate which one $SDescriptionmatches: $sdescription_1or $sdescription_2?

+4
source share
3 answers

In a scalar context, an operator =~returns the number of matches. Without a modifier, the /gnumber of matches is 0 or 1, so you can 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

}
+7
source

, - ? ( /g , \G : .)

if ($SDescription =~ /$sdescription_1/i) {
  # Do stuff for first pattern
}
elsif ($SDescription =~ /$sdescription_2/i) {
  # Do stuff for second pattern
}
+3

You can use Non-Matching Groups (? :) to accomplish this. For your code, I would try something like this:

if ($SDescription =~ m/((?:$sdescription_1))|((?:$sdescription_2))/gi) {

# $1 will hold a value IFF $sdescription_1 matches
# $2 will hold a value IFF $sdescription_2 matches

}

Whatever the “string” or pattern to display in $ 1 or $ 2. See Test Program below:

Testing program:

$str1 = "TEST1";
$str2 = "TEST2";

#Match results on $str1 (group 1)
$str1 =~ /((?:TEST1))|((?:TEST2))/;
print "[$1] [$2]\n";

#Match results on $str2 (group 2)
$str2 =~ /((?:TEST1))|((?:TEST2))/;    
print "[$1] [$2]\n";

returns the results:

[TEST1] []
[] [TEST2]
0
source

Source: https://habr.com/ru/post/1527044/


All Articles