Anand Asir
Anand Asir

Reputation: 309

How to find and replace '[' in a String?

i am having a String "['MET', 'MISSED']". Here i want to replace "[ to [ and ]" to ]. I have used the escape sequences in my String like

wkJsonStr.replaceAll("\"\\[","[");

and

wkJsonStr.replaceAll("\\]\"","]");

but none of the above worked. In 'watch' i edited like

wkJsonStr.replaceAll("\"[","["); 

and it worked. But in my Android Studio Editor this Expression is not allowed. I am getting "Unclosed character class".

I am expecting my String after replacing to be like ['MET', 'MISSED']. I want to remove the first and last quotation alone and i would like to achieve it by replaceAll method.

Upvotes: 0

Views: 107

Answers (4)

Remember that string are immutable in java...

just calling the replace method will take no effect, you need to assign the return value, otherwise will get lost.

Example:

public static void main(String[] args) {
    String wkJsonStr = "\"['MET', 'MISSED']\"";
    System.out.println(wkJsonStr);
    wkJsonStr = wkJsonStr.replaceAll("\"\\[", "[").replaceAll("\\]\"", "]");
    System.out.println(wkJsonStr);
}

this will print.

"['MET', 'MISSED']"

['MET', 'MISSED']

Upvotes: 1

Anand Asir
Anand Asir

Reputation: 309

I finally realized that the isssue is not with the Regex character. Its the Variable which i am using. when i am replacing one by one it is not forwarding the result to the next step. So i have assigned the value to a variable and now its working.

String firstResult = wkJsonStr.replaceAll("\"\\[","[");

and

String result = firstResult.replaceAll("\\]\"","]");

is working for me. Or This step will do a trick.

String result= wkJsonStr.replaceAll("\"\\[","[").replaceAll("\\]\"","]");

Upvotes: 0

Arjun saini
Arjun saini

Reputation: 4182

I agree with @Wiktor Stribiżew's comment. And you should declare your String like this:

String str = "\"['MET', 'MISSED']\""; // like this your editor will not give an error
str = str.replace("\"[","[");
str = str.replace("]\"","]");
textview.setText(str);

Upvotes: 0

dryairship
dryairship

Reputation: 6077

You can use replace instead of replaceAll, but if you really need to use replaceAll then you can do:

wkJsonStr.replaceAll("\"\\Q[\\E","[").replaceAll("\\Q]\\E\"","]")

Here,

  • \" literally denotes "
  • The part between \\Q and \\E is literally treated., i.e,
    • \\Q[\\E denotes [
    • \\Q]\\E denotes ]

Upvotes: 0

Related Questions