在使用内部使用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路径重写方法时发现了这一点,认为.*
会一次覆盖整个起始路径。