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.
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.
$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/;
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With