Get what was removed by String.replaceAll ()

So let's say I got my regex

String regex = "\d*";

      

to find any digits.

Now I also got the input line like

String input = "We got 34 apples and too much to do";

      

Now I want to replace all digits with "", doing it like this:

input = input.replaceAll(regex, "");

      

When I type the entry, I got "We have apples and too many to do." It works, he replaced 3 and 4 with "".

Now my question is, is there any way - maybe an existing library? - to get what has actually been replaced?

The example here is very simple, just to understand how it works. Want to use it for complex inputs and regular expressions.

Thank you for your help.

+3


source to share


1 answer


You can use Matcher

with add and replace procedure:



String regex = "\\d*";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

StringBuffer sb = new StringBuffer();
StringBuffer replaced = new StringBuffer();
while(matcher.find()) {
    replaced.append(matcher.group());
    matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);

System.out.println(sb.toString());  // prints the replacement result
System.out.println(replaced.toString()); // prints what was replaced

      

+2


source







All Articles