3

I have a string, say 1++++----2 and I want to replace ++++---- with a certain string, say string. The I use the java function replaceAll, but it keep warning Dangling metacharacter every time I use it:

mystring.replaceAll("++++----", "string");
The Dark Knight
  • 383
  • 1
  • 10
  • 21

4 Answers4

3

Escape the +, only the first or all doesn't matter here.

String str = "1+++---2";
str = str.replaceAll("\\+\\+\\+---", "");
System.out.println(str);

Output:

12

Or use replaceAllas it's meant to be used:

str = str.replaceAll("[+-]", "");
dly
  • 1,080
  • 1
  • 17
  • 23
2

replaceAll's first argument takes a regualr expression and + have special meaning in regualr expression. Escape + to make it work properly .

mystring.replaceAll("\\+\\+\\+\\+----", "string");
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

You can use following regex :

mystring.replaceAll("\\++-+", "string")

Since + is a regex character you need to escape it.so here in "\\++-+" the first part \\+ will match the character + literally and the second + will match 1 or more combination of character + and the rest is -+ which will match 1 or more -.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

When you replace a fixed string, you need a replace function:

String mystring  = "1++++----2";
System.out.println(mystring.replace("++++----", "string"));

See demo

Otherwise, you need a regex with replaceAll.

System.out.println(mystring.replaceAll("[+]+-+", "string"));

Note that you do not need to escape the + inside a regex character class, which is convenient in Java.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563