假设我想删除字符串周围的所有"。在Python中,我会:

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

如果我想删除多个字符,例如"和括号:

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

用Java剥离字符串的优雅方法是什么?

最佳答案



与Python代码最接近的等效项是:

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


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

如果可以使用Apache Commons Lang,那就是 StringUtils.strip()

10-06 07:26