Reputation: 6629
I'd like to replace each occurrence of a regex within a string with a parsed $1
. How can I do this?
String line = "foo <<VAR>> bar <<VAR>>";
Matcher matcher = Pattern.compile("<<(\\w*?)>>").matcher(line);
Map<String,String> replacements = Collections.singletonMap("VAR","REPLACEMENT");
String replacedLine = matcher.replaceAll(replacements.get(?.group(1)));
Assert.assertTrue("foo REPLACEMENT bar REPLACEMENT".equals(replacedLine));
Upvotes: 0
Views: 50
Reputation: 9065
Does this meet your need?
String line = "foo <<VAR>> bar <<VAR>>";
Map<String, String> replaceMap = new HashMap<>();
replaceMap.put("<<VAR>>", "REPLACEMENT");
//may be more replacement here
for(Map.Entry<String, String> entry: replaceMap.entrySet()){
line = line.replaceAll(entry.getKey(), entry.getValue());
}
System.out.println(line); //<- foo REPLACEMENT bar REPLACEMENT
Upvotes: 1
Reputation: 626689
You may use a Matcher#appendReplacement
method to build the result "as you match":
String line = "foo <<VAR>> bar <<VAR>> in <<NO>>";
Matcher m = Pattern.compile("<<(\\w+)>>").matcher(line);
Map<String,String> replacements = Collections.singletonMap("VAR","REPLACEMENT");
StringBuffer replacedLine = new StringBuffer();
while (m.find()) {
if (replacements.get(m.group(1)) != null)
m.appendReplacement(replacedLine, replacements.get(m.group(1)));
else
m.appendReplacement(replacedLine, m.group());
}
m.appendTail(replacedLine);
System.out.println(replacedLine.toString()); // => foo REPLACEMENT bar REPLACEMENT in <<NO>>
See the Java demo.
Upvotes: 1