Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
Pramod Jangam Avatar asked May 15 '15 13:05

Pramod Jangam


People also ask

What is the use of non-capturing group in regex?

A non-capturing group lets us use the grouping inside a regular expression without changing the numbers assigned to the back references (explained in the next section).

What do you put at the start of a group to make it non-capturing?

Sometimes you want to use parentheses to group parts of an expression together, but you don't want the group to capture anything from the substring it matches. To do this use (?: and ) to enclose the group.

What does a non-capturing group mean?

Non-capturing groups are important constructs within Java Regular Expressions. They create a sub-pattern that functions as a single unit but does not save the matched character sequence.

What is a regex capture group?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .


1 Answers

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"
    );
like image 86
Mena Avatar answered Sep 22 '22 12:09

Mena