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?
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).
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.
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.
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" .
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"
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With