简体   繁体   English

获取String.replaceAll()删除的内容

[英]Get what was removed by String.replaceAll()

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 "". 它有效,用“”代替了3和4。

Now my question: Is there any way - maybe an existing lib? 现在我的问题:有什么办法 - 也许是现有的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. 谢谢你的帮助。

You can use a Matcher with the append-and-replace procedure: 您可以使用具有附加和替换过程的Matcher

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM