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,010
  • 13
  • 100
  • 141
Adam Matan
  • 117,979
  • 135
  • 375
  • 532

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,109
  • 13
  • 34
  • 52
NPE
  • 464,258
  • 100
  • 912
  • 987
  • +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
  • 10,856
  • 7
  • 51
  • 84
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
  • 4,777
  • 3
  • 26
  • 34
0

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

String str = "\"te\"st\"";
str = str.replaceAll("^[\"\\(]+|[\"\\)]+$", "");
juergen d
  • 195,137
  • 36
  • 275
  • 343
-1

try this:

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

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

Adil Soomro
  • 37,173
  • 9
  • 101
  • 148
simaremare
  • 399
  • 2
  • 9