Search code examples
javareplaceall

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


In a programm like this:

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

I get the error:

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

But I want the ouput:

Hello World!

Is there are way to make userInput safe for replaceAll? Let's say the userInput is: []. How do I need to process the String to always replace the String an not the meaning of the String.


Solution

  • If you don't want the user's text to be interpreted as a regex, just use replace instead of replaceAll.

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

    Note that it replaces all occurrences of the target. The naming is a little unfortunate. Here's a summary of that the String#replace* methods do:

    • replace: replaces all verbatim occurrences.
    • replaceFirst: replaces the first regex match.
    • replaceAll: replaces all regex matches.