Get what was removed by String.replaceAll()

不羁岁月 提交于 2019-12-12 15:46:18

问题


So, let's say I got my regular expression

String regex = "\d*";

for finding any digits.

Now I also got a inputted string, for example

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

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

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

When now printing input I got "We got apples and too much to do". It works, it replaced the 3 and the 4 with "".

Now my question: Is there any way - maybe an existing lib? - to get what actually was replaced?

The example here is very simple, just to understand how it works. Want to use it for complexer inputs and regex.

Thanks for your help.


回答1:


You can use a Matcher with the append-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


来源:https://stackoverflow.com/questions/27323505/get-what-was-removed-by-string-replaceall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!