Pramod Jangam
Pramod Jangam

Reputation: 336

How to use regex non capturing group for string replace in java

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);

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

Expected outcome is [assembly: AssemblyVersion("1.0.4.0")], but I'm getting result as 4.04.0.

Can anyone please help me on this?

Upvotes: 6

Views: 2183

Answers (3)

Mena
Mena

Reputation: 48404

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"
    );

Upvotes: 9

MadConan
MadConan

Reputation: 3767

This worked for your case:

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

As an alternative to a look-behind, you can use capturing groups around what you want to keep, and keep what you want to replace in a non-capturing group or no group at all:

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

See IDEONE demo

Upvotes: 1

Related Questions