Frank
Frank

Reputation: 1130

Trimming whitespace from a String in Java

I realize there are quite a number of questions on this but I have yet to find a solution suitable for my situation. I know of string.trim() and it has no effect. After researching online and uncovering a world of hate for string.trim() I realize that the whitespace character I am trying to remove must be out of the range .trim() caters for.

I am using some regex, which I do not fully understand, to strip the string of any special characters excluding '=' and ',' and all whitespace EXCEPT if it is immediately after the ','.

However, I now want to completely remove all whitespace from the string. Any ideas of how to edit the regex I am using to accomplish this would be appreciated. Again, what I want is '=' and ',' along with digits and letters to remain. All whitespace and other special characters should be removed.

Here's the code so far:

if (argsToBeFiltered != null) {
            // Remove all whitespace and chars apart from = and ,
            String filteredArgs = argsToBeFiltered.replaceAll(
                    "[^=,\\da-zA-Z\\s]|(?<!,)\\s", "");
            return filteredArgs;
}

Upvotes: 5

Views: 5025

Answers (2)

CoolBeans
CoolBeans

Reputation: 20800

Try this:-

if (argsToBeFiltered != null) {
            // Remove all whitespace and chars apart from = and ,
            String filteredArgs = argsToBeFiltered.replaceAll(
                    "\\w+");
            return filteredArgs;
}

Upvotes: 1

user166390
user166390

Reputation:

Time to learn a regular expression!

See Pattern and various regular expression tutorials such as Lesson: Regular Expressions.

[^=,\\da-zA-Z\\s]

That part says match NOT (^) the characters: =, ,, digits (\d), A-Z (A-Z) or whitespace (\s). However, you likely want it to match spaces now (as there is no second after-comma part to match them). So:

argsToBeFiltered.replaceAll("[^=,\\da-zA-Z]", "");

Upvotes: 5

Related Questions