javaapache-stringutils

Replace different combinations of whitespaces, tabs and carriage returns with a single white space


I would likwe to replace different combinations of whitespaces, tabs and carriage returns with a single white space.

So far i got a solution that works:

String stringValue="";
stringValue = stringValue.replaceAll(";", ",");
stringValue = stringValue.replaceAll("\\\\n+", " ");
stringValue = stringValue.replaceAll("\\\\r+", " ");
stringValue = stringValue.replaceAll("\\\\t+", " ");
stringValue = stringValue.replaceAll(" +", " ");

Input: test\n\t\r123 ;123 Output:test123,123

is there a prettier solution to this ?


Solution

  • The \s class matches whitespace characters. Thus:

    stringValue = stringValue.replaceAll("\\s+", " ");
    

    To substitute whitespace escape strings per the question, the four regexes can be combined as follows:

    "(?:\\\\[nrt])+| +"