6

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?

2
  • I ran this and you don't have any groups in that pattern. Are you looking to use capturing groups? Commented May 15, 2015 at 13:28
  • [assembly: AssemblyVersion("1.0 This I want as non capturing group 0.0 I want as capturing group ")] I want as non capturing group. So that only bug fix number (third digit) and build number (fourth digit) gets replaced but whole pattern is used for matching. Commented May 15, 2015 at 13:34

3 Answers 3

9

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"
    );
Sign up to request clarification or add additional context in comments.

1 Comment

The reason this works and your example didn't is because your call String.replaceAll() doesn't use capturing groups. What replaceAll() does is take everything that matches the regex and replace it with the replacement value. Look-(ahead/behind) will do what you want because they're "zero-length" assertions: the regex will only match your string if the look-ahead behind is there, but those parts of the pattern won't "count" as part of the matched String, so they won't be replaced.
1

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

Comments

0

This worked for your case:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.