3

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

 1 year ago
source link: https://www.pkslow.com/archives/idea-regex-replace-with-matched-value
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

敢一行,则予知。脚踏实地,知行合一。

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

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-regex-replace-with-matched-value.match.png

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

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

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

替换语句如下:

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

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

idea-regex-replace-with-matched-value.regex.png

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

idea-regex-replace-with-matched-value.result.png

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


Code for all: GitHub

欢迎关注微信公众号<南瓜慢说>,将持续为你更新...

file

Recommendations:
Cloud Native
Terraform
Container: Docker/Kubernetes
Spring Boot / Spring Cloud
Https
如何制定切实可行的计划并好好执行


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK