-2

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

Reto
  • 1,305
  • 1
  • 18
  • 32
  • The code you've posted isn't valid, in various ways. Please make sure you post code that actually compiles, unless you're asking about compile-time errors. – Jon Skeet Dec 23 '16 at 08:57
  • Java or JavaScript? `removeAll()`? Could you please adjust the question/tags? – Wiktor Stribiżew Dec 23 '16 at 08:57
  • @Wiktor Stribiżew JAVA – Reto Dec 23 '16 at 09:11
  • So please post valid Java code - and clarify your requirements. (See the comment on my answer. It's not clear whether that's the desired behaviour or not.) – Jon Skeet Dec 23 '16 at 09:19
  • Nope, code still doesn't compile, and if you're calling `replace` that doesn't use regular expressions at all. You also still haven't clarified your requirements. A [mcve] (showing multiple inputs and expected outputs) would help an awful lot. – Jon Skeet Dec 23 '16 at 09:24
  • What is not clear here? `// expected result // some string // some "other string"` – Reto Dec 23 '16 at 09:24
  • Probably a dupe of http://stackoverflow.com/questions/2608665/how-can-i-trim-beginning-and-ending-double-quotes-from-a-string/41298589#41298589 – Wiktor Stribiżew Dec 23 '16 at 09:25
  • @Wiktor Stribiżew Nope, only double quotes there, while I need to remove single and double quotes at both ends – Reto Dec 23 '16 at 09:30
  • @Reto: Well it's not clear as your code still doesn't compile to start with (the declaration for `two`), and there are multiple cases you should be considering and giving your expected output for. Please be aware that the more effort you put into making your question clear, the better the answers will be. – Jon Skeet Dec 23 '16 at 09:38
  • @Reto: It *is* a dupe: http://stackoverflow.com/a/41298589/3832970 – Wiktor Stribiżew Dec 23 '16 at 09:42
  • @Jon Skeet sorry, I was not aware of the issue with the declaration of `two` - now the question about `JAVA`or `JS`make sense to me! – Reto Dec 23 '16 at 09:43
  • @Reto: And this is why I suggested posting a [mcve]. That way you'd have compiled and run it yourself, and found the solution. – Jon Skeet Dec 23 '16 at 09:43
  • @Wiktor Stribiżew In fact not the question of the "dupe" matches, but your answer does. By the way - you answer there `str.replaceAll("^[\"']+|[\"']+$")`does also not compile - it should be `str.replaceAll("^[\"']+|[\"']+$","")` - Errare Humanum Est ;) – Reto Dec 23 '16 at 09:52

4 Answers4

7

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'
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

To complete Jon Skeet response, if you want to remove quotes only if there is one on the beginning AND one on the end you can do :

public String removeQuotes(String str) {
  Pattern pattern = Pattern.compile("^['\"](.*)['\"]$");
  Matcher matcher = pattern.matcher(str);
  if (matcher.find()) {
    return matcher.group(1);
  } else {
    return str;
  }
}
Oreste Viron
  • 3,592
  • 3
  • 22
  • 34
  • I have no use cases. And [your code, same as Skeet's, does not work as expected](https://ideone.com/9vjnPS). – Wiktor Stribiżew Dec 23 '16 at 09:19
  • Sorry, I assumed wrong that you are the original poster. – Oreste Viron Dec 23 '16 at 09:20
  • Can you give an exemple that don't work with my code ? – Oreste Viron Dec 23 '16 at 09:20
  • This one works perfectly for my use case (see expected result) - thanks! – Reto Dec 23 '16 at 09:26
  • @Reto: Are you happy for a string of `"foo'` to end up as `foo`? This code doesn't currently check that the quotes at the start and end are the same. (It's also still unclear whether you ever want it to be able to remove more than one character from the start and end.) – Jon Skeet Dec 23 '16 at 09:38
  • 1
    Finally, this would be more simply written as `return str.replaceAll("^['\"](.*)['\"]$", "$1");` – Jon Skeet Dec 23 '16 at 09:39
  • @John Skeet sorry for not beeing precise enough! I've updated my question. Great answer of yours, by the way! – Reto Dec 23 '16 at 12:33
0

if you are looking in javascript try this :

   function t(k){
    var l="\"\'"; //you can add more chars here.
     if (l.indexOf(k[0])>-1) {
    return t(k.substr(1,k.length));
        } else if (l.indexOf(k[k.length-1])>-1) {
    return t(k.substr(0,k.length-1));
        } else {
     return k;
    }
    }
Jayanti Lal
  • 1,175
  • 6
  • 18
0

One possible way with using replaceFirst():

String one = "\"some string\"";         
System.out.println("one: " + one);               
one = one.replaceFirst("\"", "");
String reversed = new StringBuilder(one).reverse().toString();
one = one.replaceFirst("\"", "");    
one = new StringBuilder(reversed).reverse().toString();
System.out.println("result: " + one);
Nurjan
  • 5,889
  • 5
  • 34
  • 54