Python的str.strip()的Java等价物

Ada*_*tan 11 java string

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

>>> s='"Don\'t need the quotes"'
>>> print s
"Don't need the quotes"
>>> print s.strip('"')
Don't need the quotes
Run Code Online (Sandbox Code Playgroud)

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

>> s='"(Don\'t need quotes and parens)"'
>>> print s
"(Don't need quotes and parens)"
>>> print s.strip('"()')
Don't need quotes and parens
Run Code Online (Sandbox Code Playgroud)

在Java中删除字符串的优雅方法是什么?

NPE*_*NPE 10

假设我想删除所有"周围的字符串

与Python代码最接近的是:

s = s.replaceAll("^\"+", "").replaceAll("\"+$", "");
Run Code Online (Sandbox Code Playgroud)

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

s = s.replaceAll("^[\"()]+", "").replaceAll("[\"()]+$", "");
Run Code Online (Sandbox Code Playgroud)

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


Phi*_*ler 6

番石榴库中有它一个方便的工具.该库包含CharMatcher.trimFrom(),它可以满足您的需求.您只需要创建一个CharMatcher匹配您要删除的字符.

码:

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

CharMatcher matcher2 = CharMatcher.anyOf("\"()");
System.out.println(matcher2.trimFrom(s));
Run Code Online (Sandbox Code Playgroud)

在内部,这不会创建任何新的String,而只是调用s.subSequence().因为它也不需要Regexps,我想它是最快的解决方案(当然也是最干净,最容易理解的).