Trimming whitespace from a string in Java

I understand that there are a number of issues in this, but I still have to find a solution that is suitable for my situation. I know string.trim () and has no effect. After exploring online and uncovering the hate world for string.trim (), I understand that the whitespace I'm trying to remove must be outside the range of .trim () serves.

I use some kind of regular expression, which I don’t quite understand, to remove the line of any special characters, excluding "=" and ",", and all EXCEPT spaces, if they are immediately after ",".

However, now I want to completely remove all spaces from the string. Any ideas on how to edit the regex that I use to achieve this will be appreciated. Again, I want the "=" and "," along with numbers and letters to remain. All spaces and other special characters must be removed.

Here is the code:

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

Time to learn regex!

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

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

NOT (^) : =, ,, (\ d), A-Z (A-Z) (\ s). , , , , ( , ). :

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

: -

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

All Articles