How to use regex non capture group to replace string in java

I had a requirement to change AssemblyVersionto a new assembly. I am doing this with java codestring.replaceAll(regexPattern,updatedString);

This code works fine with regular regex patterns, but I can't use groups without capture in this pattern. I want to use groups without capture to make sure that I do not collect templates other than required. 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);

Here I want to match a string [assembly: AssemblyVersion(int.int)]and replace only a minor version.

Expected result [assembly: AssemblyVersion("1.0.4.0")], but I get the result as 4.04.0.

Can anyone help me with this?

+4
source share
3 answers

/ ?

:

str = str
    .replaceAll(
        "(?<=\\[assembly: AssemblyVersion\\(\"\\d\\.\\d\\.).*(?=\"\\)\\])",      
        "4.0"
    );
+7

, , , , :

String str="[assembly: AssemblyVersion(\"1.0.0.0\")]";
str=str.replaceAll("(\\[assembly:\\s*AssemblyVersion\\(\"\\d+\\.\\d+\\.)\\d+\\.\\d+(?=\"\\)\\])", "$014.0");
System.out.println(str);

IDEONE

+1

This worked for your case:

str.replaceAll("(\\[assembly: AssemblyVersion\\(\"\\d\\.\\d\\.)(\\d\\.\\d)(\"\\)\\])", "$14.0$3");
0
source

All Articles