假设我想删除所有 "
围绕一个字符串。在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()
。
该 番石榴 库有一个方便的实用程序。该库包含 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,我猜它是最快的解决方案(当然也是最干净,最容易理解的)。
在java中,你可以这样做:
s = s.replaceAll("\"",""),replaceAll("'","")
此外,如果您只想替换“开始”和“结束”引号,您可以执行以下操作:
s = s.replace("^'", "").replace("'$", "").replace("^\"", "").replace("\"$", "");
或者如果简单地说:
s = s.replaceAll("^\"|\"$", "").replaceAll("^'|'$", "");
尝试这个:
new String newS = s.replaceAll("\"", "");
用无字符串替换双引号。
这取代了 "
和 ()
在字符串的开头和结尾
String str = "\"te\"st\"";
str = str.replaceAll("^[\"\\(]+|[\"\\)]+$", "");