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

时间:2012-03-06 12:11:26

标签: java string

假设我想删除字符串周围的所有"。在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中删除字符串的优雅方法是什么?

5 个答案:

答案 0 :(得分:10)

  

假设我想删除字符串

周围的所有"

与Python代码最接近的是:

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

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

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

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

答案 1 :(得分:6)

Guava库有一个方便的实用程序。该库包含CharMatcher.trimFrom(),可以满足您的需求。您只需要创建一个匹配您要删除的字符的CharMatcher

代码:

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

CharMatcher matcher2 = CharMatcher.anyOf("\"()");
System.out.println(matcher2.trimFrom(s));

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

答案 2 :(得分:1)

在java中,你可以这样做:

s = s.replaceAll("\"",""),replaceAll("'","")

此外,如果您只想替换“开始”和“结束”引号,您可以执行以下操作:

s = s.replace("^'", "").replace("'$", "").replace("^\"", "").replace("\"$", "");

或者如果简单地说:

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

答案 3 :(得分:0)

这会在字符串的开头和结尾替换"()

String str = "\"te\"st\"";
str = str.replaceAll("^[\"\\(]+|[\"\\)]+$", "");

答案 4 :(得分:0)

试试这个:

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

用无字符串替换双引号。