那么,假设我得到了我的正则表达式
String regex = "\d*";
用于查找任何数字。
现在我也得到了一个输入的字符串,例如
String input = "We got 34 apples and too much to do";
现在我想用“”替换所有数字,这样做:
input = input.replaceAll(regex, "");
当现在打印输入时,我得到“We got apples and too much to do”。它有效,它用“”替换了 3 和 4。
现在我的问题是:有什么办法——也许是现有的库? - 得到实际被替换的东西?
这里的例子很简单,只是为了理解它是如何工作的。想要将它用于更复杂的输入和正则表达式。
感谢您的帮助。
最佳答案
您可以将 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
关于java - 获取 String.replaceAll() 删除的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27323505/