Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 377
BbIKTOP Avatar asked Feb 07 '23 15:02

BbIKTOP


1 Answers

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");
like image 141
Mifmif Avatar answered Feb 09 '23 05:02

Mifmif