Take the 2-minute tour ×

I would like to trim a beginning and ending double quote (") from a string.
How can I achieve that in Java? Thanks!

share|improve this question
Is the string already known to have quotes around it, or is checking for quotes part of the problem? –  Michael Myers Apr 9 '10 at 15:39
add comment

3 Answers

up vote 40 down vote accepted

You can use String#replaceAll() with a pattern of ^\"|\"$ for this.


string = string.replaceAll("^\"|\"$", "");

To learn more about regular expressions, have al ook at http://regular-expression.info.

That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.

share|improve this answer
I'm not building a csv parser. i'm building a facebook app using tinyfbclient and for some reason it provides me the uid of the user with trailing and ending double quotes. –  ufk Apr 9 '10 at 15:36
don't you think it will replaces all occurrences of double quotes with empty string rather then the first and the last. –  GuruKulki Apr 9 '10 at 15:36
@ufk: This isn't a complex regex. You may otherwise want to hassle with a bunch of String#indexOf(), String#substring(), methods and so on. It's only a little tad faster, but it's much more code. @GK: Uh, did you read/understand the regex or even test it? –  BalusC Apr 9 '10 at 15:37
@GK the caret represents the beginning of the searched string, and the dollar sign represents its end. The backslash here "escapes" the following quote so it's treated as just a character. So this regex says, replace all occurrences of quote at the start, or quote at the end, with the empty string. Just as requested. –  Carl Manaster Apr 9 '10 at 15:53
@GK: Carl's right. Also, replace() methods doesn't accept regex. They accept only a char or a literal string (charsequence). The replaceAll() method is the only accepting a regex to match character patterns for replacement. –  BalusC Apr 9 '10 at 16:28
show 2 more comments

To remove the first character and last character from the string, use:

myString = myString.substring(1, myString.length()-1);
share|improve this answer
This only requires that the quotes should guaranteed be present. If there's no guarantee, then you'll need to check it first beforehand. –  BalusC Apr 9 '10 at 15:32
@BalusC: Certainly. From my reading of the question, it seems that the string is already known to have quotes around it. –  Michael Myers Apr 9 '10 at 15:36
add comment

find indexes of each double quotes and insert an empty string there.

share|improve this answer
But watch out for quotes in the middle... –  David Gelhar Apr 9 '10 at 15:36
so it should be first index and the last index of double qoute. –  GuruKulki Apr 9 '10 at 15:39
add comment

Your Answer


