获取 String.replaceAll() 删除的内容 [英] Get what was removed by String.replaceAll()

查看:48
本文介绍了获取 String.replaceAll() 删除的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,假设我得到了我的正则表达式

So, let's say I got my regular expression

String regex = "\d*";

用于查找任何数字.

现在我也得到了一个输入的字符串,例如

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, "");

当现在打印输入时,我得到我们有苹果还有太多事情要做".它有效,它用"替换了 3 和 4.

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.

感谢您的帮助.

推荐答案

您可以将 Matcher 与 append-and-replace 过程一起使用:

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

这篇关于获取 String.replaceAll() 删除的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆