In an Android app, I am looking for the functionality of the .NET string function [Trim(‘aaa’)] which will trim off the text “aaa” off a string. I don’t think this is natively available in Java and I haven’t seen that functionality in Android Java textutil library.
Is there an easy way to have a Java app trim a set of characters from the string?
Regex trimming
The specification isn’t clear, but you can use regular expression to do this.
Here’s an example:
The anchors
\Aand\Zmatch the beginning and end of the input respectively.|is alternation.\dis the shorthand for the digit character class.+is “one-or-more-of” repetition specifier. Thus, the pattern\d+\Zis regex-speak for “sequence of digits at the end of the input”.References
java.util.regex.PatternLiteral trimming
If you just want a literal suffix/prefix chopping, then no regex is required. Here’s an example:
Then we can have: