我需要替换字符串中可能可用或不可用的某些部分,并且在Perl s///
中返回进行替换的次数。如果根本没有替换任何东西,这可以很容易地用来回答这个问题。我正在尝试使用Matcher.replaceAll
在Java中执行相同的操作,尽管它似乎具有matching result internally,但是我看不到任何访问它的方法。这样一来,我要么比较返回的字符串和输入的字符串是否有差异,要么自己先匹配正则表达式,然后仅在需要时使用replaceAll
,然后似乎再次匹配该字符串。
或者我是否缺少某些东西,并且可以查询一些状态/标志?
答案 0 :(得分:3)
如果您使用的是Java 9,则Matcher类提供了一个称为results()的方法,该方法返回Stream。您可以执行以下操作:
int count = matcher.results().count();
答案 1 :(得分:2)
您可以使用模式匹配器,仅保留匹配项的计数。下面的代码是一种慢动作,更可控,可以进行正则表达式替换。例如,我假设您要用dog
替换所有出现的cat
。
String line = "There was a big dog, larger than the other dog.";
String pattern = "\\bdog\\b";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
int count = 0;
StringBuffer buff = new StringBuffer();
while (m.find()) {
m.appendReplacement(buff, "cat");
++count;
}
m.appendTail(buff);
System.out.println(buff.toString());
System.out.println("There were " + count + " matches.");
输出:
There was a big cat, larger than the other cat.
There were 2 matches.
请注意,您暗示了一个比上述方法更聪明,更简单的解决方案。我们可以比较正则表达式替换前后的字符串长度。但是,我们不能在我给出的示例中使用此方法,因为开始和替换字符串的长度恰好相同。