Re: how to run regex calculation

2020-01-12 Thread Paul B. Henson
On Thu, Jan 09, 2020 at 10:36:19AM +0800, Wesley Peng wrote:

> $str = "2 3 6";
> 
> I want to match with:
> 
> true if $str =~ /(\d+)\s(\d+)\s($1*$2)/;
> 
> that's to say, the thrid column would be (firstCol * SecondCol).
> 
> How to write regex for this?

I don't think you can do it directly in the regex. You'll need to do the
math separately:

if ($str =~ /^(\d+)\s(\d+)\s(\d+)$/ && $3 == $1 * $2) {
print "true\n"
}
else {
print "false\n";
}


Re: how to run regex calculation

2020-01-12 Thread Alex Mestiashvili

I am not subscribed to the list, so sending to the authors too.

This seem to work:

echo "2 3 6" |perl -Mstrict -pE 's{(\d+)\s(\d+)\s(\d+)}{my 
$r="false";$r="true" if $3 == eval"$1*$2";$r}e;'


perl -Mstrict -lE 'my $str = "2 3 7"; $str =~ s{(\d+)\s(\d+)\s(\d+)}{my 
$result="false";$result="true" if $3 == eval"$1*$2";$result}e;say $str'


The magic is the /e modifier.

Regards,
Alex

On 1/9/20 5:25 PM, MIchael Capone wrote:
It probably won't ever work.  The problem is the * (star/asterisk) after 
\1 is being interpreted in the context of regular expressions, ie, 
"zero-or-more matches", and not as a multiplication operator.  In fact,


~]$ perl -Mstrict -le 'my $str = "2 3 23"; print "true" if 
$str=~/(\d+)\s(\d+)\s(\1*\2)/'


...does indeed print "true"

It would probably make the most sense to not try to do this as a 
one-liner (why do we perl programmers love to be cute like that?), and 
simply break it up into two steps:


$str =~ s/(\d+)\s(\d+)\s(\d+)/;
print "true" if ($1*$2 == $3);

- Michael



On 1/9/2020 12:39 AM, Wesley Peng wrote:

Hallo

on 2020/1/9 16:35, demerphq wrote:

$str=~/(\d+)\s(\d+)\s(\1*\2)/

$1 refers to the capture buffers from the last completed match, \1
inside of the pattern part of a regex refers to the capture buffer of
the currently matching regex.


This doesn't work too.

perl -Mstrict -le 'my $str = "2 3 6"; print "true" if 
$str=~/(\d+)\s(\d+)\s(\1*\2)/'


nothing printed.


Regards.