leonz leonz - 1 year ago 99
Android Question

Android "()" not treated as string

I have a problem with one line of code, which goes like this:

string = string.replaceAll("sin()", "");

As you can see, in a string, all "sin()" need to be replaced with "". But the problem is that () is not treated as string and so this line of code replaces "sin()" with "()". Moreover, Android studio reports warning on the () saying empty group. I tried solving this with escape character, but that doesn't work. Would following code work by any chance?

String compare = "sin()";
string = string.replaceAll(compare, "");

Answer Source

replaceAll's first parameter is a regular expression, of which ( and ) are special characters. You would instead need to use

string = string.replaceAll("sin\\(\\)", "");

Note the use of \\ - \ is actually a special character in Java strings, so you must first escape the \ by using \\.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download