Search code examples
regexperl

splitting the string with regex - print $2 twice


I have the code:

#!/bin/env perl
use warnings;
$line = 'GFHFHDSH4567 FHGFF           687686';
print $line, "\n";
$line =~ s/ +/ /g;
$line =~ s/^(.+)(?=\s+(\d+)$)/1:$1\t2:$2/g;
print $line, "\n";

I get:

GFHFHDSH4567 FHGFF 687686
1:GFHFHDSH4567 FHGFF 2:687686 687686

Why it printed twice?


Solution

  • Your regex includes a look-ahead assertion. This doesn't form part of the final matched string, so only the first part of $line, 'GFHFHDSH4567 ', is replaced with the replacement string '1:GFHFHDSH4567 FHGFF 2:687686' The original '687686' is left unchanged.