Capturing matching content of two different regular expressions in perl

I use a while loop with two separate regular expressions

while(($string1=~m/(\d+)/igs)==($string2=~m/([^^]*?)\n+/igs)) {} 

to save the value of the matching string pattern $ string1, I used $temp1=$1 ,

How to save a matching $string2 pattern. Please give some suggestion.

+7
regex perl
source share
3 answers
 my ($m1,$m2); while (do{ ($m1,$m2) = (); $m1 = $1 if $string1 =~ /(\d+)/igs; $m2 = $1 if $string2 =~ /([^^]*?)\n+/igs; defined $m1 == defined $m2; }) { # print "$m1-$m2-\n"; } 
+5
source share

There may be smarter ways, but I would just decompose them into separate statements:

 while (1) { $res1 = $string1=~m/(\d+)/igs; $temp1 = $1; $res2 = $string2=~m/([^^]*?)\n+/igs $temp2 = $1; last unless $res1 == $res2; ... } 

Just because perl doesn’t need you to look for the shortest, cryptic way to write something (what APL is for).

+3
source share

If the parameters "g" and "s" are not really needed for your task, and you really want to compare only matching substrings, you can do a one-line test as follows:

 if (($a =~ /regex1/)[0] == ($b =~ regex2/)[0]) { ... 

And if you need to know which two lines matched, just add temporary variables to hold them:

 if (($first = ($a =~ /regex1/)[0]) == ($second = ($b =~ regex2/)[0])) { ... 

But if you really want to compare all consecutive matches on each line to make sure that each pair is the same, there is no solution with a single expression that I can think of doing it. Your regular expressions return a list, and "==" compares their lengths. You should use the first solution suggested above and write the comparison code in "long-hand".

The second solution above will not work, as it will only check the first match on each line.

It’s a little difficult to understand what you are trying to do, but you could at least discard the “i” option in the first test for / (\ d +) /. Presumably, the s parameter is only needed for the second line, as you are looking for inline newlines.

0
source share

All Articles