假设我想删除字符串周围的所有 "
。在 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 中去除字符串的优雅方法是什么?
最佳答案
Suppose I would like to remove all
"
surrounding a string
最接近 Python 代码的是:
s = s.replaceAll("^\"+", "").replaceAll("\"+$", "");
And if I want to remove multiple characters, e.g.
"
and parentheses:
s = s.replaceAll("^[\"()]+", "").replaceAll("[\"()]+$", "");
如果可以使用Apache Commons Lang , 有 StringUtils.strip()
.
关于Python 的 str.strip() 的 Java 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9583467/