如何在Java中使用正则表达式非捕获组进行字符串替换 [英] How to use regex non capturing group for string replace in java
问题描述
我需要在新版本中更改AssemblyVersion
.我使用Java代码string.replaceAll(regexPattern,updatedString);
I had a requirement to change AssemblyVersion
on new build. I do it using java code string.replaceAll(regexPattern,updatedString);
此代码可以在正常的正则表达式模式下正常工作,但是我无法在此模式下使用非捕获组.我想使用非捕获组来确保除了捕获所需的模式以外,不捕获其他模式.这是我尝试的代码:
This code works fine with normal regex patterns, but I am not able to use non-capturing groups in this pattern. I want to use non-capturing groups to make sure I don't capture patterns other than required one. This is the code I tried:
String str="[assembly: AssemblyVersion(\"1.0.0.0\")]";
str=str.replaceAll("(?:\\[assembly: AssemblyVersion\\(\"\\d\\.\\d\\.)?.*(?:\"\\)\\])?", "4.0");
System.out.println(str);
在这里,我想匹配字符串[assembly: AssemblyVersion(int.int)]
并仅替换次要版本.
Here, I want to match string [assembly: AssemblyVersion(int.int)]
and replace only minor version.
预期结果为[assembly: AssemblyVersion("1.0.4.0")]
,但我得到的结果为4.04.0
.
Expected outcome is [assembly: AssemblyVersion("1.0.4.0")]
, but I'm getting result as 4.04.0
.
有人可以帮我吗?
推荐答案
为什么不使用先行搜索/后向搜索?
Why not use look-ahead / look-behind instead?
它们不具有捕获性,可以在这里轻松工作:
They are non-capturing and would work easily here:
str = str
.replaceAll(
"(?<=\\[assembly: AssemblyVersion\\(\"\\d\\.\\d\\.).*(?=\"\\)\\])",
"4.0"
);
这篇关于如何在Java中使用正则表达式非捕获组进行字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!