Home > Software engineering >  java String.replaceFirst(old, new): How to interpret old as a literal and NOT a regex?
java String.replaceFirst(old, new): How to interpret old as a literal and NOT a regex?

Time:11-14

For example

String s1 = "buT [A-Z]";
s1.replaceFirst("[A-Z]", "999");

This would return "bu999 [A-Z]". However, I want the old string "[A-Z]" interpreted as a string and NOT a regex, and the desired result is "buT 999".

How can I do that?

CodePudding user response:

s1.replaceFirst("\\[A-Z]", "999");

CodePudding user response:

You could leverage Pattern.quote:

String s1 = "buT [A-Z]";
s1.replaceFirst(Pattern.quote("[A-Z]"), "999");
  • Related