Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent for Python's str.strip()

Tags:

java

string

Suppose I would like to remove all " surrounding a string. In Python, I would:

>>> 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, e.g. " 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?

like image 264
Adam Matan Avatar asked Mar 06 '12 12:03

Adam Matan


People also ask

Is there a strip method in Java?

strip() is an instance method that returns a string whose value is the string with all leading and trailing white spaces removed. This method was introduced in Java 11. If the string contains only white spaces, then applying this method will result in an empty string.

How do you strip a line in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

What does the strip () do in Python?

The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.

Does Java have sets like Python?

The set interface is present in java. util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored.


2 Answers

Suppose I would like to remove all " surrounding a string

The closest equivalent to the Python code is:

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

And if I want to remove multiple characters, e.g. " and parentheses:

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

If you can use Apache Commons Lang, there's StringUtils.strip().

like image 145
NPE Avatar answered Sep 18 '22 17:09

NPE


The Guava library has a handy utility for it. The library contains CharMatcher.trimFrom(), which does what you want. You just need to create a CharMatcher which matches the characters you want to remove.

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(). As it also doesn't need Regexps, I guess its the fastest solution (and surely the cleanest and easiest to understand).

like image 28
Philipp Wendler Avatar answered Sep 21 '22 17:09

Philipp Wendler