[英]Java equivalent for Python's str.strip()
Suppose I would like to remove all "
surrounding a string. In Python, I would: 假设我想删除所有
"
围绕一个字符串。在Python中,我会:
>>> s='"Don\'t need the quotes"'
>>> print s
"Don't need the quotes"
>>> print s.strip('"')
Don't need the quotes
And if I want to remove multiple characters, eg "
and parentheses: 如果我想删除多个字符,例如
"
和括号:
>> s='"(Don\'t need quotes and parens)"'
>>> print s
"(Don't need quotes and parens)"
>>> print s.strip('"()')
Don't need quotes and parens
What's the elegant way to strip a string in Java? 在Java中删除字符串的优雅方法是什么?
Suppose I would like to remove all
"
surrounding a string假设我想删除所有
"
围绕一个字符串
The closest equivalent to the Python code is: 与Python代码最接近的是:
s = s.replaceAll("^\"+", "").replaceAll("\"+$", "");
And if I want to remove multiple characters, eg
"
and parentheses:如果我想删除多个字符,例如
"
和括号:
s = s.replaceAll("^[\"()]+", "").replaceAll("[\"()]+$", "");
If you can use Apache Commons Lang , there's StringUtils.strip()
. 如果你可以使用Apache Commons Lang ,那就是
StringUtils.strip()
。
The Guava library has a handy utility for it. Guava库有一个方便的实用程序。 The library contains
CharMatcher.trimFrom()
, which does what you want. 该库包含
CharMatcher.trimFrom()
,它CharMatcher.trimFrom()
您的需求。 You just need to create a CharMatcher
which matches the characters you want to remove. 您只需创建一个与要删除的字符匹配的
CharMatcher
。
Code: 码:
CharMatcher matcher = CharMatcher.is('"');
System.out.println(matcher.trimFrom(s));
CharMatcher matcher2 = CharMatcher.anyOf("\"()");
System.out.println(matcher2.trimFrom(s));
Internally, this does not create any new String, but just calls s.subSequence()
. 在内部,这不会创建任何新的String,而只是调用
s.subSequence()
。 As it also doesn't need Regexps, I guess its the fastest solution (and surely the cleanest and easiest to understand). 因为它也不需要Regexps,我想它是最快的解决方案(当然也是最干净,最容易理解的)。
In java, you can do it like : 在java中,你可以这样做:
s = s.replaceAll("\"",""),replaceAll("'","")
Also if you only want to replace "Start" and "End" quotes, you can do something like : 此外,如果您只想替换“开始”和“结束”引号,您可以执行以下操作:
s = s.replace("^'", "").replace("'$", "").replace("^\"", "").replace("\"$", "");
OR if simply put : 或者如果简单地说:
s = s.replaceAll("^\"|\"$", "").replaceAll("^'|'$", "");
This replaces "
and ()
at the beginning and end of a string 这将在字符串的开头和结尾替换
"
and ()
"
String str = "\"te\"st\"";
str = str.replaceAll("^[\"\\(]+|[\"\\)]+$", "");
try this: 尝试这个:
new String newS = s.replaceAll("\"", "");
replace the double-quote with a no-character String. 用无字符串替换双引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.