I would like to remove single or double quotes from both ends of a string. The string may contain additional quotes or/and double quotes which shall remain untouched - so removeAll()
is not an option.
String one = "\"some string\"";
String two = "'some \"other string\"'";
// expected result
// some string
// some "other string"
What I tried so far:
two = two.replace("/^[\"\'])|([\"\']$/g", "");
The following would work but there must be a much more elegant way to achieve this..
if ((one != null && one.length() > 1) && ((one.startsWith("\"") && one.endsWith("\"")) ||
(one.startsWith("\'") && one.endsWith("\'")))) {
one = one.substring(1, one.length() - 1);
}
Any ideas?
Update / clarification
My use case is the command line interface of an app, where the user can also drag files/paths into, instead of typing them.
Under Windows the dragged files are beeing surrounded by double quotes, under Linux with single quotes. All I want to do is get rid of them. So in my use case the quotes are always symetric (they match).
But I can perfectly live with a solution, which would strip them even if they wouldn't match, because they always do
Option 1: Removing all single and double quotes from start and end
You can use replaceAll
which accepts a regular expression - replace
doesn't - and do it twice, once for quotes at the start of the string and once for quotes at the end:
public class Test {
public static void main(String[] args) {
String text = "\"'some \"other string\"'";
String trimmed = text
.replaceAll("^['\"]*", "")
.replaceAll("['\"]*$", "");
System.out.println(trimmed);
}
}
The ^
in the first replacement anchors the quotes to the start of the string; the $
in the second anchors the quotes to the end of the string.
Note that this doesn't try to "match" quotes at all, unlike your later code.
Option 2: Removing a single quote character from start and end, if they match
String trimmed = text.replaceAll("^(['\"])(.*)\\1$", "$2");
This will trim exactly one character from the start and end, if they both match. Sample:
public class Test {
public static void main(String[] args) {
trim("\"foo\"");
trim("'foo'");
trim("\"bar'");
trim("'bar\"");
trim("\"'baz'\"");
}
static void trim(String text) {
String trimmed = text.replaceAll("^(['\"])(.*)\\1$", "$2");
System.out.println(text + " => " + trimmed);
}
}
Output:
"foo" => foo
'foo' => foo
"bar' => "bar'
'bar" => 'bar"
"'baz'" => 'baz'
See more on this question at Stackoverflow