Swap String contents for "$"

0

I have a String with a content and I need to do a replaceAll, however the text to be replaced contains a dollar sign "$" and this causes the error Illegal group reference .

Example:

    String texto="teste {{texto}} teste";
    String trocar="_$_";
    texto=texto.replaceAll("\{\{texto\}\}", trocar);

Note: This "swap" String comes from a database, so I can not add the \. The example is illustrative only.

    
asked by anonymous 08.03.2017 / 21:27

3 answers

2

Failed to use escape \

public static void main(String[] args) {
    String texto = "teste {{texto}} teste";
    String trocar = "_\$_";
    texto = texto.replaceAll("\{\{texto\}\}", trocar);
    System.out.println(texto);
}

You can still use quote to make searching easier:

String buscar = Pattern.quote("{{texto}}");
texto = texto.replaceAll(buscar, trocar);

Now the value coming from another source, you can solve by trying to escape $ by \$ a way to do this:

public static void main(String[] args) {
    String texto = "teste {{texto}} teste";
    String origem = "_$_";
    String trocar = origem.replaceAll(Pattern.quote("$"), "\\\$");
    String buscar = Pattern.quote("{{texto}}");
    texto = texto.replaceAll(buscar, trocar);
    System.out.println(texto);
}
    
08.03.2017 / 21:30
2

String.replaceAll" takes a regular expression matching pattern as its first parameter, and a regular expression substitution pattern as its second parameter - and $ has a specific meaning in regular expressions (in both matching patterns and patterns of substitution, though in different senses).

Just use String.replace instead, and I suspect all your problems will go away. You should only use replaceAll when you really want to match / replace through a regular expression - which I do not think you do in this case.

    
08.03.2017 / 21:43
0

Use scape:

public static void main(String[] args) {
        String texto="teste {{texto}} teste";
        String trocar="_\$_";
        texto=texto.replaceAll("\{\{texto\}\}", trocar);
        System.out.println(texto);

    }
    
08.03.2017 / 21:31