如何使 .replaceAll(String regex, String replacement) 中的正则表达式对用户输入安全?

How to make the regex from .replaceAll(String regex, String replacement) safe for Userinput?

在这样的程序中:

String userInput = "[]";
String str = "Hello World[]!";
String replacement = "";
str = str.replaceAll(userInput, replacement);
System.out.print(str);

我收到错误:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 1
[]

但我想要输出:

Hello World!

有没有办法让 userInput 对 replaceAll 安全?假设 userInput 是:[]。我需要如何处理字符串以始终替换字符串而不是字符串的含义。

您可以显式quote输入字符串:

String normal = "[]";
System.out.println(normal);
System.out.println(Pattern.quote(normal));

[]
\Q[]\E

如果您不希望用户的文本被解释为正则表达式,只需使用 replace 而不是 replaceAll

String str = "foo bar [] baz []";
String userInput = "[]";
String replacement = "moo";
str = str.replace(userInput, replacement);
// str = "foo bar moo baz moo"

请注意,它替换了目标的 所有 次出现。命名有点不幸。以下是 String#replace* 方法所做的总结:

  • replace: 逐字替换。
  • replaceFirst: 替换第一个正则表达式匹配。
  • replaceAll: 替换所有正则表达式匹配。