Using replace function in Java

Dipanjan Mallick :

I am trying to use replace function to replace "('", "'" and "')" from the below string -

String foo = "('UK', 'IT', 'DE')";

I am trying to use the below code in order to do this operation -

(foo.contains("('")?foo.replaceAll("('", ""):foo.replace("'",""))?foo.replaceAll("')",""):foo

but its failing as -

java.util.regex.PatternSyntaxException: Unclosed group near index 2

Am I missing anything here?

Konrad Rudolph :

replaceAll takes a regular expression as its search pattern. Since ( is a special character in regular expressions, it need to be escaped: '\\('. Furthermore, there’s no need for the contains test:

final String bar = foo.replaceAll("\\('", "") …

Lastly, you can combine all your replacements into one regular expression:

final String bar = foo.replaceAll("\\(?'([^']*)'\\)?", "$1");
// Output: UK, IT, DE

This will replace each occurrence of a single-quoted part inside your string with its content without the quotes, and it will allow (and discard) surrounding opening and closing parentheses.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296383&siteId=1