BbIKTOP BbIKTOP - 5 months ago 32
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:

[\s,(](%variable)[\s,)$]


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);
while(m.find())
{
System.println(m.group(1));
}


Upd:
The solution is to set the captures to whole regex:

([\s,(])(%variable)([\s,)$])


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

Answer

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