Java 如何使regex from.replaceAll(String regex,String replacement)对用户输入安全?

Java 如何使regex from.replaceAll(String regex,String replacement)对用户输入安全?,java,replaceall,Java,Replaceall,在这样的程序中: 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 chara

在这样的程序中:

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!
有没有办法让用户输入对replaceAll安全?假设用户输入为:
[]
。我需要如何处理字符串以始终替换字符串,而不是字符串的含义

您可以显式输入字符串:

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


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

String str=“foo bar[]baz[]”;
字符串userInput=“[]”;
字符串替换=“moo”;
str=str.replace(用户输入,替换);
//str=“foo bar moo baz moo”
请注意,它将替换目标的所有引用。这个名字有点不幸。下面总结一下
String#replace*
方法的作用:

  • replace
    :替换所有逐字出现的内容
  • replaceFirst
    :替换第一个正则表达式匹配项
  • replaceAll
    :替换所有正则表达式匹配项

请提供示例。您的问题描述不够清楚。