182

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

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
ufk
  • 30,912
  • 70
  • 235
  • 386

18 Answers18

309

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

E.g.

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 7
    don't you think it will replaces all occurrences of double quotes with empty string rather then the first and the last. – GuruKulki Apr 09 '10 at 15:36
  • 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 09 '10 at 15:36
  • 1
    @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 09 '10 at 15:37
  • i checked. it does not replace all occurrences of double quotes. only the first and the last. – ufk Apr 09 '10 at 15:39
  • sorry BalusC i am not good at Regex, as you have used replaceAll, i had a doubt on that. – GuruKulki Apr 09 '10 at 15:40
  • 18
    @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 09 '10 at 15:53
  • 1
    @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 09 '10 at 16:28
  • 1
    How can I replace only pair start/end quotes and leave single quote? – Konstantin Konopko Nov 28 '14 at 00:34
  • 1
    This doesn't work if the string has a double quote at the beginning only. It will still match the regex...... – Marc May 16 '15 at 11:36
  • 3
    @Marc: I'm not sure how that's a problem considering the question in its current form. – BalusC May 16 '15 at 17:40
  • 1
    This is the correct answer if you want to remove starting and ending double quotes from a string. – Ionut Negru Sep 20 '16 at 10:43
  • 10
    Here is the regex broken down: `^\"|\"$`. `|` means "or". It will thus match either `^\"` or `\"$`. `^` matches start of string and `$` matches end of string. `^\"` means match a quote at the start of the string and `\"$` matches a quote at the end of the string. – ibizaman Jan 02 '17 at 07:12
  • Regular expression should be /^\"|\"$/ this actually give a compilation error – Pablo Pazos Sep 01 '21 at 18:03
  • @PabloPazos: that can happen if you're confusing Java with JavaScript. – BalusC Sep 01 '21 at 18:34
37

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

myString = myString.substring(1, myString.length()-1);
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • 27
    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 09 '10 at 15:32
  • 4
    @BalusC: Certainly. From my reading of the question, it seems that the string is already known to have quotes around it. – Michael Myers Apr 09 '10 at 15:36
27

Also with Apache StringUtils.strip():

 StringUtils.strip(null, *)          = null
 StringUtils.strip("", *)            = ""
 StringUtils.strip("abc", null)      = "abc"
 StringUtils.strip("  abc", null)    = "abc"
 StringUtils.strip("abc  ", null)    = "abc"
 StringUtils.strip(" abc ", null)    = "abc"
 StringUtils.strip("  abcyx", "xyz") = "  abc"

So,

final String SchrodingersQuotedString = "may or may not be quoted";
StringUtils.strip(SchrodingersQuotedString, "\""); //quoted no more

This method works both with quoted and unquoted strings as shown in my example. The only downside is, it will not look for strictly matched quotes, only leading and trailing quote characters (ie. no distinction between "partially and "fully" quoted strings).

rath
  • 3,655
  • 1
  • 40
  • 53
21

If the double quotes only exist at the beginning and the end, a simple code as this would work perfectly:

string = string.replace("\"", "");

sunraincyq
  • 644
  • 1
  • 6
  • 15
21

Kotlin

In Kotlin you can use String.removeSurrounding(delimiter: CharSequence)

E.g.

string.removeSurrounding("\"")

Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter. Otherwise returns this string unchanged.

The source code looks like this:

public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)

public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
    if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
        return substring(prefix.length, length - suffix.length)
    }
    return this
}
Ryan Amaral
  • 4,059
  • 1
  • 41
  • 39
17

This is the best way I found, to strip double quotes from the beginning and end of a string.

someString.replace (/(^")|("$)/g, '')
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Yaniv Levi
  • 456
  • 6
  • 8
14

First, we check to see if the String is doubled quoted, and if so, remove them. You can skip the conditional if in fact you know it's double quoted.

if (string.length() >= 2 && string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"')
{
    string = string.substring(1, string.length() - 1);
}
brcolow
  • 1,042
  • 2
  • 11
  • 33
  • This is the most performant answer by orders of magnitude and it even specifies what to do regarding the optional or not presence of the quotes. – entonio Sep 25 '17 at 18:01
12

Using Guava you can write more elegantly CharMatcher.is('\"').trimFrom(mystring);

legrass
  • 407
  • 5
  • 13
  • 3
    is it possible to trim only single character? For example if my string ends with two single quotes still I want only single quote to get trimmed. – vatsal mevada Aug 18 '15 at 14:19
6

I am using something as simple as this :

if(str.startsWith("\"") && str.endsWith("\""))
        {
            str = str.substring(1, str.length()-1);
        }
utkarsh
  • 409
  • 5
  • 7
4

To remove one or more double quotes from the start and end of a string in Java, you need to use a regex based solution:

String result = input_str.replaceAll("^\"+|\"+$", "");

If you need to also remove single quotes:

String result = input_str.replaceAll("^[\"']+|[\"']+$", "");

NOTE: If your string contains " inside, this approach might lead to issues (e.g. "Name": "John" => Name": "John).

See a Java demo here:

String input_str = "\"'some string'\"";
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
System.out.println(result); // => some string
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
4

Edited: Just realized that I should specify that this works only if both of them exists. Otherwise the string is not considered quoted. Such scenario appeared for me when working with CSV files.

org.apache.commons.lang3.StringUtils.unwrap("\"abc\"", "\"")    = "abc"
org.apache.commons.lang3.StringUtils.unwrap("\"abc", "\"")    = "\"abc"
org.apache.commons.lang3.StringUtils.unwrap("abc\"", "\"")    = "abc\""
raisercostin
  • 8,777
  • 5
  • 67
  • 76
3

The pattern below, when used with java.util.regex.Matcher, will match any string between double quotes without affecting occurrences of double quotes inside the string:

"[^\"][\\p{Print}]*[^\"]"
Andrei Sfat
  • 8,440
  • 5
  • 49
  • 69
Alex F
  • 89
  • 5
2
Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
    strUnquoted = m.group(1);
}
Ravikiran
  • 29
  • 1
2

Modifying @brcolow's answer a bit

if (string != null && string.length() >= 2 && string.startsWith("\"") && string.endsWith("\"") {
    string = string.substring(1, string.length() - 1);
}
Albatross
  • 669
  • 7
  • 24
  • I would think that the method argument should be annotated with `@NonNull` and it should probably have something like `Objects.requireNonNull(string)` inside of it because if someone is calling stripQuotes(null) they are probably doing so by mistake! – brcolow Aug 03 '19 at 19:04
1
private static String removeQuotesFromStartAndEndOfString(String inputStr) {
    String result = inputStr;
    int firstQuote = inputStr.indexOf('\"');
    int lastQuote = result.lastIndexOf('\"');
    int strLength = inputStr.length();
    if (firstQuote == 0 && lastQuote == strLength - 1) {
        result = result.substring(1, strLength - 1);
    }
    return result;
}
m0untp
  • 19
  • 1
0

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

GuruKulki
  • 25,776
  • 50
  • 140
  • 201
0
public String removeDoubleQuotes(String request) {
    return request.replace("\"", "");
}
  • 5
    This question already contains multiple answers and an accepted answer. Can you explain (by editing your answer) where your answer differs from the other answers? Also know that Code-only answers are not useful in the long run. – 7uc1f3r Oct 02 '20 at 19:51
  • 5
    This was already suggested in this answer https://stackoverflow.com/a/25452078/1839439 please do not add another one. – Dharman Oct 02 '20 at 21:57
-1

Groovy

You can subtract a substring from a string using a regular expression in groovy:

String unquotedString = theString - ~/^"/ - ~/"$/
Joman68
  • 2,248
  • 3
  • 34
  • 36