Adam Matan Adam Matan - 2 months ago 18
Java Question

Java equivalent for Python's str.strip()

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?

NPE NPE
Answer

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