Is there a way to replace only one captured group in java matcher regex?
<p>I need to find and replace substrings in java, for example variable names that begins with '%', using regex like that:</p>

<pre><code>[\s,(](%variable)[\s,)$]
</code></pre>

<p>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.<br>
Here's the code sample that I use for search:</p>

<pre><code>Matcher m=Pattern.compile(regex).matcher(str);
while(m.find())
{
   System.println(m.group(1));
}
</code></pre>

<p>Upd:
The solution is to set the captures to whole regex:</p>

<pre><code>([\s,(])(%variable)([\s,)$])
</code></pre>

<p>And to use replaceAll("$1"+replacement+"$3") then</p>