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

一曲冷凌霜 提交于 2019-11-26 22:15:42

问题


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


回答1:


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.




回答2:


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

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



回答3:


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

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




回答4:


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

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



回答5:


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




回答6:


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



回答7:


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




回答8:


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
}



回答9:


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



回答10:


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



回答11:


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




回答12:


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



回答13:


Modifying @brcolow's answer a bit

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



回答14:


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



回答15:


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




回答16:


Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
    strUnquoted = m.group(1);
}


来源:https://stackoverflow.com/questions/2608665/how-can-i-trim-beginning-and-ending-double-quotes-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!