[java] How can I trim beginning and ending double quotes from a string?

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

This question is related to java string trim

The answer is


Scala

s.stripPrefix("\"").stripSuffix("\"")

This works regardless of whether the string has or does not have quotes at the start and / or end.

Edit: Sorry, Scala only


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

someString.replace (/(^")|("$)/g, '')

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

myString = myString.substring(1, myString.length()-1);

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);
}

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
}

Modifying @brcolow's answer a bit

if (string != null && string.length() >= 2 && string.startsWith("\"") && string.endsWith("\"") {
    string = string.substring(1, string.length() - 1);
}

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).


public String removeDoubleQuotes(String request) {
    return request.replace("\"", "");
}

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\""

I am using something as simple as this :

if(str.startsWith("\"") && str.endsWith("\""))
        {
            str = str.substring(1, str.length()-1);
        }

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

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


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}]*[^\"]"

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

Groovy

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

String unquotedString = theString - ~/^"/ - ~/"$/

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


Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
    strUnquoted = m.group(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;
}

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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to trim

How to remove whitespace from a string in typescript? Strip / trim all strings of a dataframe Best way to verify string is empty or null Does swift have a trim method on String? Trim specific character from a string Trim whitespace from a String Remove last specific character in a string c# How to delete specific characters from a string in Ruby? How to Remove the last char of String in C#? How to use a TRIM function in SQL Server