Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex works in python simulator but not in perl

Tags:

python

regex

perl

Hello I´m using an online regex simulator to test that what I´m writing is correct: I want to extract information from the following texts:

Test23242asdsa 800,03 23.05.19 22.05.19
Tdsadas,tsadsa test 1.020,03 23.05.19 22.05.19
Test,23242 0,03 23.05.19 22.05.19

I try to use the same code in perl:

use strict;
my $entry = 'Test23242asdsa 0,03 23.05.19 22.05.19';
my ($name, $expense, $date_expense, $date_paid) = $1, $2, $3, $4 if ($entry =~ m/^(.+)\s((?:\d+\.)?\d{1,3},\d{2})\s(\d{2}\.\d{2}\.\d{2})\s(\d{2}\.\d{2}\.\d{2})$/);
print "Name: '$name', Expense: '$expense', Date: '$date_expense', Date Paid: '$date_paid' \n";

And if I use the same regex here:

https://regex101.com/
^(.+)\s((?:\d+\.)?\d{1,3},\d{2})\s(\d{2}\.\d{2}\.\d{2})\s(\d{2}\.\d{2}\.\d{2})$

It detects de regex correctly. I though python and perl used the same regex syntax, so I don´t get what is going on.

like image 308
nck Avatar asked Jan 01 '23 02:01

nck


1 Answers

The regexp is fine, the problem is with how you're setting the variables.

You need to wrap $1, $2, $3, $4 in parentheses to do list assignment, because of Perl's operator precedence.

Change it to

my ($name, $expense, $date_expense, $date_paid) = ($1, $2, $3, $4) if ($entry =~ m/^(.+)\s((?:\d+\.)?\d{1,3},\d{2})\s(\d{2}\.\d{2}\.\d{2})\s(\d{2}\.\d{2}\.\d{2})$/);

working demo

like image 87
Barmar Avatar answered Jan 09 '23 19:01

Barmar