LarryDpk
发布于 2022-12-15 / 400 阅读
0

Intellij IDEA利用正则替换,并保留匹配结果

需求

需求是这样的,我需要将:

https://github.com/LarryDpk/pkslow-samples/tree/master/other/spring-batch/remote-partition-local

转换成:

[/other/spring-batch/remote-partition-local](https://github.com/LarryDpk/pkslow-samples/tree/master/other/spring-batch/remote-partition-local)

但数量非常多。需要找到母字符串和子串/other/spring-batch/remote-partition-local,并按一点规则替换掉整个母字符串。转换前如下图:

正则替换

IDEA提供了强大的正则功能,可以把匹配的子串作为变量来使用,这样便可以满足需求了。我的匹配语句如下:

https://github.com/LarryDpk/pkslow-samples/tree/master(?<path>.*?)$

这里就会把path作为一个变量,匹配到对应的字符串赋值给它。

替换语句如下:

[${path}](https://github.com/LarryDpk/pkslow-samples/tree/master${path})

这里就可以使用path这个变量了,极其方便有用。如下图所示:

它还给出来替换后的结果显示,挺人性化的。替换后结果如下:


References:
https://www.jetbrains.com/help/idea/tutorial-finding-and-replacing-text-using-regular-expressions.html