12

Suppose I would like to remove all " surrounding a string. In Python, I would:

>>> s='"Don\'t need the quotes"'
>>> print s
"Don't need the quotes"
>>> print s.strip('"')
Don't need the quotes

And if I want to remove multiple characters, e.g. " and parentheses:

>> s='"(Don\'t need quotes and parens)"'
>>> print s
"(Don't need quotes and parens)"
>>> print s.strip('"()')
Don't need quotes and parens

What's the elegant way to strip a string in Java?

Charles
  • 50,943
  • 13
  • 104
  • 142
Adam Matan
  • 128,757
  • 147
  • 397
  • 562

5 Answers5

12

Suppose I would like to remove all " surrounding a string

The closest equivalent to the Python code is:

s = s.replaceAll("^\"+", "").replaceAll("\"+$", "");

And if I want to remove multiple characters, e.g. " and parentheses:

s = s.replaceAll("^[\"()]+", "").replaceAll("[\"()]+$", "");

If you can use Apache Commons Lang, there's StringUtils.strip().

Draken
  • 3,134
  • 13
  • 34
  • 54
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • +1 For handling multiple characters as requested. It still creates two new Strings, though. – Adam Matan Mar 06 '12 at 12:28
  • 1
    @AdamMatan: I think Common Lang's `StringUtils.strip()` is the preferred method. See my updated answer. – NPE Mar 06 '12 at 12:30
6

The Guava library has a handy utility for it. The library contains CharMatcher.trimFrom(), which does what you want. You just need to create a CharMatcher which matches the characters you want to remove.

Code:

CharMatcher matcher = CharMatcher.is('"');
System.out.println(matcher.trimFrom(s));

CharMatcher matcher2 = CharMatcher.anyOf("\"()");
System.out.println(matcher2.trimFrom(s));

Internally, this does not create any new String, but just calls s.subSequence(). As it also doesn't need Regexps, I guess its the fastest solution (and surely the cleanest and easiest to understand).

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87
1

In java, you can do it like :

s = s.replaceAll("\"",""),replaceAll("'","")

Also if you only want to replace "Start" and "End" quotes, you can do something like :

s = s.replace("^'", "").replace("'$", "").replace("^\"", "").replace("\"$", "");

OR if simply put :

s = s.replaceAll("^\"|\"$", "").replaceAll("^'|'$", "");
Ramandeep Singh
  • 5,063
  • 3
  • 28
  • 34
0

This replaces " and () at the beginning and end of a string

String str = "\"te\"st\"";
str = str.replaceAll("^[\"\\(]+|[\"\\)]+$", "");
juergen d
  • 201,996
  • 37
  • 293
  • 362
-1

try this:

new String newS = s.replaceAll("\"", "");

replace the double-quote with a no-character String.

Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
simaremare
  • 401
  • 2
  • 10