0

I have the next string:

String var = "Hello NAME_USER, welcome to NAME_USER, your name is NAME_USER";

I want to replace all occurrences of NAME_USER, the problem is when NAME_USER has special characters (ex: !"#$%&/()=)(/&%), a java.lang.IllegalArgumentException is thrown.

The complete code:

String var = "Hello NAME_USER, welcome to NAME_USER, your name is NAME_USER";
var = var.replaceAll("NAME_USER","!#$%&/()=)(/&%");

The exception:

java.lang.IllegalArgumentException: Illegal group reference
    at java.util.regex.Matcher.appendReplacement(Matcher.java:857)
    at java.util.regex.Matcher.replaceAll(Matcher.java:955)
    at java.lang.String.replaceAll(String.java:2210)
    at com.vupc.colegios.infraestructura.utilitarios.UtilitarioPlantilla.reemplazarTexto(UtilitarioPlantilla.java:119)

Note: NAME_USER can be replace by any String.

Is there any way to solve this?

Whymarrh
  • 13,139
  • 14
  • 57
  • 108
victorpacheco3107
  • 822
  • 3
  • 10
  • 32

2 Answers2

1

Use String#replace() instead of String#replaceAll()

or String#format() with numerated arguments:

String var = String.format("Hello %1$s, welcome to %1$s, your name is %1$s", username);
ifloop
  • 8,079
  • 2
  • 26
  • 35
0

Use String.replace(CharSequence,CharSequence).

Andreas Berheim Brudin
  • 2,214
  • 1
  • 18
  • 13