In perl I have a long string but here is the important part $abc = "...Testvalue1 100...";
Is there a way to use Regex to search for the number right after Testvalue# and replace it with a variable?
Here is what I have so far:
my $abc = "...Testvalue1 100...";
for my $i (1..100) {
$abc =~ s/Testvalue\d+\W+(\d+)/$i/;
print $abc . "\n";
}
Unfortunately this replace the entire match with $i
, not just the first match of (\\d+). Is there a way to do this?
My desired output would be:
Testvalue1 1
Testvalue1 2
...
Testvalue1 100
If you're using Perl 5.10 or newer:
$abc =~ s/ Testvalue \d+ \s+ \K \d+ /$i/x;
(mnemonic for \\K
: "keep" everything to the left)
If you're not:
$abc =~ s/ ( Testvalue \d+ \s+ ) \d+ /$1$i/x;
(capturing the data you don't want to lose).
In Perl you can use:
$abc =~ s/Testvalue\d+\W+\K\d+/$i/;
\\K
resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.