Java replace capturing group with different value
java, regex
Solution
Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference. There's a bunch of Java-specific information in there, particularly in the "Flavor-Specific Information" section.
This works:
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Replacement {
public static final void main(String[] ignored) {
String str = "fname:hello hello:world ffff:off";
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "meme");
mapping.put("hello", "below");
mapping.put("ffff", "ssss");
Pattern pat = Pattern.compile("([a-zA-Z_]+):");
Matcher m = pat.matcher(str);
StringBuffer sb = new StringBuffer();
while(m.find()) {
String rplcWith = mapping.get(m.group(1));
m.appendReplacement(sb, rplcWith + ":");
}
m.appendTail(sb);
System.out.println(sb);
}
}
Output:
[C:\java_code\]java Replacement
meme:hello below:world ssss:off
Problem
In java I want to replace only the capturing group in the matched part with some other value and the value to be replaced depends on the capturing group. Eg: ``` String str = "fname:hello hello:world ffff:off"; Map<String, String> mapping = new HashMap<String, String>(); dat.put("fname", "meme"); dat.put("hello", "below"); dat.put("ffff", "ssss"); Pattern pat = Pattern.compile("([a-zA-Z_]+):"); ``` In the above code I want to replace the capturing group part of the pattern "pat" with the corresponding mapping found in the "mapping". i.e. After the replacement the "str" string should be transformed to "meme:hello below:world ssss:off" How can I achieve this? Thanks for the help.