可以不丢失匹配的字符串吗?

Possible to not lose the matched string?

如果我这样做

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

然后我必须在替换端添加 ",就像我在匹配端添加 .*?" 一样,因此丢失了 ",因此必须替换它再次.

问题

我可以不用再添加 " 吗?

这是我的测试用例:

$ 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"

您应该在 perlre 中检查 "Look-Around Assertions"。

使用正向预测(?=):

(?=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.*?(?=")

因此,此处尾随 " 将匹配,但不会在 $& 中被捕获。