SRam
SRam

Reputation: 2828

how to replace string "[quote]" to only " and [/quote] to "

I need to replace all [quote] to " and [/quote] to " of following string:

[quote]fgfhfgh [quote] vbbb[/quote]ghhhhjj[/quote] 

The result should be like :

"fghfdgfdh "gghj vbbb"ghhhhjj"

I used this but unable to do:

finalRecieveString = (String) uivdHashTable.get("pendingString");
String ReplaceQuote=finalRecieveString.replaceAll("[quote]", "\"");
ReplaceFinalQuoteString=ReplaceQuote.replaceAll("[/quote]", "\"");

Upvotes: 0

Views: 131

Answers (2)

Manoj Manani
Manoj Manani

Reputation: 507

String string = "[quote]mucho grando wrote: [quote]mucho grando wrote: vbbb[/quote]ghhhhjj[/quote]";

String tmp_str = string.replace("\[quote]", "\"");

String str_ans = tmp_str.replace("\[/quote]", "\"");

your ans str_ans = "mucho grando wrote: "mucho grando wrote: vbbb"ghhhhjj"

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

You have to escape square brackets, as replaceAll() expects regexp which brackets are part of syntax of. So try:

finalRecieveString = (String) uivdHashTable.get("pendingString");
String ReplaceQuote=finalRecieveString.replaceAll("\[quote\]", "\"");
ReplaceFinalQuoteString=ReplaceQuote.replaceAll("\[/quote\]", "\"");

You could also chain the replace:

ReplaceFinalQuoteString = finalRecieveString.replaceAll("\[quote\]", "\"").replaceAll("\[/quote\]", "\"");

PS: adding spaces around "=" increases code readability.

Upvotes: 3

Related Questions