Jasmine Lognnes Jasmine Lognnes - 5 months ago 12
Perl Question

Possible to not lose the matched string?

If I do

perl -i -slpe 's/$wgDBserver = "\K.*?"/$ip"/' -- -ip=$IP test


then I have to add the
"
on the replace side, as I do
.*?"
on the matching side, and therefore lose the
"
, and therefore have to replace it again.

Question

Is it possible to not having to add the
"
again my self?

Here is my test case:

$ IP="123.456.78.9" && \
echo -n '\n\n$wgDBserver = "172.17.0.3";\naaa "123"\n\n\n' > test && \
perl -i -slpe 's/$wgDBserver = "\K.*?"/$ip"/' -- -ip=$IP test && \
cat test


$wgDBserver = "123.456.78.9";
aaa "123"

Answer

You should check "Look-Around Assertions" in perlre.

Use positive lookahead(?=):

(?=pattern) : A zero-width positive look-ahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $& .

"\K.*?(?=")

So, here trailing " will match, but will not get captured in $&.

Comments