BbIKTOP BbIKTOP - 1 year ago 63
Java Question

Is there a way to replace only one captured group in java matcher regex?

I need to find and replace substrings in java, for example variable names that begins with '%', using regex like that:


I'd like to find all variables, store their names and to replace them to some placeholder then, for example %%. Cannot find how is it possible in java, please help. Matcher#replaceAll replaces whole regexp but I need to replace just first group, not the whole occurrence.

Here's the code sample that I use for search:

Matcher m=Pattern.compile(regex).matcher(str);

The solution is to set the captures to whole regex:


And to use replaceAll("$1"+replacement+"$3") then


You can keep some groups of your regex and replace others in the occurences found in a string . if we suppose that your regex is : [\\s,\\(](%variable)[\\s,$] , then you can use the replaceAll() method of java.lang.String. You need first to set your regex in the form of saparate groups

ex:([\\s,\\(])(%variable)([\\s,$]), so you have

The 1st group is : [\\s,\\(]

The second group is %variable

And the third group is [\\s,$] , now you can set reference of your groups the final value that will replace each occurence found in your regex ,for example if we want to replace the second group with the string 'myNewVal' the code will be :

String myRegex = "([\\s,\\(])(%variable)([\\s,$])";
String replacedValue = originalValue.replaceAll(myRegex,"$1myNewVal$3");

$1 and $3 refer to the first and the third group, we keep them in the replaceValue.

if you want just remove the second group you can try this :

String myRegex = "([\\s,\\(])(%variable)([\\s,$])";
String replacedValue = originalValue.replaceAll(myRegex,"$1$3");