lapots
lapots

Reputation: 13415

apply escaping for regex matches

I have such replacement statement

output.replaceAll(REGEX_BRACKETS, "<$2$3>");

How to apply escaping via (StringEscapeUtils for example) for $2 and $3?

Upvotes: 2

Views: 39

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

Here is an example of how this can be done inside Matcher:

String s = "word 123 some text inside next 567";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("(\\w+)\\s+(\\d+)").matcher(s);
while (m.find()) {
    String wrd = m.group(1);
    String num = m.group(2);
    String replacement = wrd.toUpperCase() + num;
    m.appendReplacement(result, replacement);
}
m.appendTail(result);
System.out.println(result.toString());

See IDEONE demo

Just use your own functions, I am using toUpperCase() just for demo.

Upvotes: 1

Related Questions