Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate $1 with number in a regex

Tags:

regex

perl

I would like to insert the number between two patterns:

$s = 'id="" value="div"';
$s =~ s/(id=")(".*)/$1123$2/;

Of course I got the error and " value="div" as a result. The expected result is id="123" value="div".

In the replacement I meant $1, then number 123 and then $2, but not $1123 and then $2. What is the correct replacement in the regex? I would like to do it in one single regex.

Thanks.

like image 227
Alex Broitman Avatar asked Aug 01 '12 15:08

Alex Broitman


People also ask

How do you concatenate expressions in RegEx?

To concatenate a regular expression in JavaScript, you can use a combination of the + operator and the RegExp() class as shown below. You need to combine both the RegExp source (the string representation of the RegExp) and flags (options for the RegExp). You are responsible for removing duplicate flags.


2 Answers

$s =~ s/(id=")(".*)/$1123$2/;  # Use of uninitialized value $1123 in concatenation (.) or string

Though you expected it to substitute for $1, perl sees it as the variable $1123. Perl has no way to know that you meant $1. So you need to limit the variablisation to $1 by specifying it as ${1}:

$s =~ s/(id=")(".*)/${1}123$2/;

It is always a good idea to include the following at the top of your scripts. They will save you a lot of time and effort.

use strict;
use warnings;

For example, running your script with the above modules included results in the error message:

Use of uninitialized value $1123 in concatenation (.) or string at /tmp/test.pl line 7.

(Disregard the reported script name and line numbers.) It clearly states what perl expected.

Another approach using look-behind and look-ahead assertions:

$s =~ s/(?<=id=")(?=")/123/;
like image 198
Alan Haggai Alavi Avatar answered Dec 30 '22 04:12

Alan Haggai Alavi


Another variant:

$s =~ s/(id=")(".*)/$1."123".$2/e;

Usage example:

$ cat 1.pl
$s = 'id="" value="div"';
$s =~ s/(id=")(".*)/$1."123".$2/e;
print $s,"\n";

$ perl 1.pl
id="123" value="div"
like image 31
Igor Chubin Avatar answered Dec 30 '22 03:12

Igor Chubin