-3

I'm trying to search for a substring in a string and replace it. I'm using

String p= "+ 0.0";

But this line gives me a dangling metacharacter error. I've tried typecasting this but it still doesn't work. How do I fix this?

I want to do the following

if(s.containts(p)){ //s is a given string
s.replaceAll(p,"");
}

On a related note,

s.containts("+ 0.0")) throws no dangling metacharater error but s.replaceAll("+ 0.0",""); throws the error.

Is there a reason for this?

Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
pasha
  • 406
  • 1
  • 4
  • 17
  • So what exactly are you doing with that `p` variable, is that what you eventually use as a regular expression during replacement? Then this is basically the same issue as here, https://stackoverflow.com/questions/917822/ – 04FS Mar 07 '19 at 13:46
  • 2
    Apparently you’re performing a regex match operation. So you need to learn about [the syntax](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html), to quote meta characters or just use [`Pattern.quote`](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#quote-java.lang.String-)… In case you’re using `String.replaceAll(String,String)`, just consider using [`String.replace(CharSequence,CharSequence)`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-java.lang.CharSequence-java.lang.CharSequence-) instead. – Holger Mar 07 '19 at 13:50
  • The obvious method to use is [`replace`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-java.lang.CharSequence-java.lang.CharSequence-), which does not produce "dangling metacharacter" errors. Apparently you're using something different, though you have not posted a [mcve]. – khelwood Mar 07 '19 at 13:53
  • take a look at https://stackoverflow.com/questions/4316710/string-replaceall-without-regex – Paulo Filipe Dantas Mar 07 '19 at 15:23

1 Answers1

-1

Escape the + and ., since + and . are meta characters of a regular expression.

String p= "\\+ 0\\.0";
nice_dev
  • 17,053
  • 2
  • 21
  • 35