Naseem
Naseem

Reputation: 961

Replace is not replacing double quotes in java

I have a below string which is coming from the application:

Hotel “Lowest Rate Guaranteed” Terms and Conditions

I am trying to replace double quotes in the above statement using following line:

Tempdata = Tempdata.replace("\"", "");
System.out.println(Tempdata);

It's not working and always returning the same value but if I manually remove the above double quote and enter the double quote manually and try the same command, it works fine.

After replacing the double quote manually, the string looks like

Hotel "Lowest Rate Guaranteed" Terms and Conditions

We can see there is minor difference in the double quote. Look like the double quote which is coming from application is utf-8.

Appreciate any help. Thanks

Upvotes: 0

Views: 3521

Answers (1)

Insomniac
Insomniac

Reputation: 446

You could just copy the double quotes into the replace, the respective codes are \u201c and \u201d.

Alternatively you could use a regular expression such as [\"'\u2018\u2019\u201c\u201d] to match all quotes. (Not however those characters often misused as quotation marks. I'm looking at you, `grave and acute´)

Where

  • " matches "
  • ' matches '
  • \u2018 matches (left single quotation mark)
  • \u2019 matches (right single quotation mark)
  • \u201c matches (left double quotation mark)
  • \u201d matches (right double quotation mark)

An example of this could be just using String.replaceAll():

tempdata = tempdata.replaceAll("[\"'\u2018\u2019\u201c\u201d]", "")

Or, if you need to do this often, compiling the pattern and saving is more efficient:

Somewhere in your class:

private final Pattern quotation = Pattern.compile("[\"'\u2018\u2019\u201c\u201d]") 

And then further down:

quotation.matcher(tempdata).replaceAll("")

On an unrelated note, don't give variables capital names in Java, it burns my eyes and is against all common convention. Giving them the same name as a class is extra evil.

Upvotes: 5

Related Questions