Douy789
Douy789

Reputation: 1161

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 ?

Upvotes: 0

Views: 164

Answers (1)

jsheeran
jsheeran

Reputation: 3037

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])+| +"

Upvotes: 1

Related Questions