String#replaceAll的行为背后的解释是什么

时间:2019-03-05 10:07:18

标签: java regex replaceall

在使用内部使用Java String#replaceAll()方法的API时,我注意到一些令我惊讶的东西:

String path = "/test";
String newPath = path.replaceAll(".*", "/status");
System.out.println(newPath);
// prints /status/status

也就是说,.*正则表达式模式似乎已匹配两次,并且每个匹配项都向新路径添加了一个/status。另一方面,如果我们使用模式^.*$,则会得到我实际上期望的行为:

String path = "/test";
String newPath = path.replaceAll("^.*$", "/status");
System.out.println(newPath);
// prints /status

我确信阅读Matcher的实现代码将解释这种现象。但是我希望有人能引起人们对为什么为什么Java希望.*多次匹配输入字符串?这对我来说似乎违反直觉。

注意:我在使用Spring的网关API路径重写方法时发现了这一点,认为.*会一次覆盖整个起始路径。

0 个答案:

没有答案