Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String replaceAll() method using {} curly brackets

So for my app in Android Studio I want to replace the following:

String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
            String replacedCard = card.replaceAll("{Player1}", "Poep");
}

An example of String card can be: {Player1} switch drinks with the person next to you.

Somehow I can't use {} for the replacing. With the { it says: "Dangling metacharacter". Screenshot: https://prnt.sc/s2bbl8

Is there a solution for this?

like image 571
Daniëlle Avatar asked Sep 06 '25 03:09

Daniëlle


1 Answers

the first Argument of replaceAll is a String that is parsed to a regular Expression (regEx). The braces { } are special reserved meta characters to express something within the regular expression. To match them as normal characters, you need to escape them with a leading backslash \ and because the backslash is also a special character you need to escape itself with an additional backslash:

String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
like image 138
Simulant Avatar answered Sep 07 '25 19:09

Simulant