简体   繁体   English

为什么 String.replaceAll(".*", "REPLACEMENT") 在 Java 8 中会出现意外行为?

[英]Why does String.replaceAll(".*", "REPLACEMENT") give unexpected behavior in Java 8?

Java 8's String.replaceAll(regexStr, replacementStr) doesn't work when the regex given is ".*".当给定的正则表达式为“.*”时,Java 8 的 String.replaceAll(regexStr, replacementStr) 不起作用。 The result is double the replacementStr.结果是replacementStr 的两倍。 For example:例如:

String regexStr = ".*";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);

// Expected Result: finalStr == "REPLACEMENT"
// Actual Result: finalStr == "REPLACEMENTREPLACEMENT"

I know replaceAll() doesn't exactly make sense to use when the regex is ".*", but the regex isn't hardcoded and could be other regex strings.我知道当正则表达式为“.*”时,replaceAll() 使用起来并不完全有意义,但正则表达式不是硬编码的,可能是其他正则表达式字符串。 Why doesn't this work?为什么这不起作用? Is it a bug in Java 8?这是Java 8中的错误吗?

// specify start and end of line

String regexStr = "^.*$";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM