jama
jama

Reputation: 21

Java String: remove all other whitespaces before and after line breaks

I need to remove heading and tailing whitespaces which is done with .trim(), also i need replace all line breaks by single space which is done with .replaceAll("\\R+", " ") but before that i need to remove all whitespaces (except line breaks) before and after line break.

String toReplace = "\t\t random \t\n\r\t text \t\t";
String result = toReplace.replaceAll(Some magic, "")
                         .replaceAll("\\R+", " ")
                         .trim();

Assert.assertEquals("random text", result);

Thank you.

Upvotes: 1

Views: 704

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You can match the whitespaces around the line breaks and remove them together with the line break replacement with space:

String result = toReplace.replaceAll("\\h*\\R+\\h*", " ").trim();

The regex is \h*\R+\h*, and the .replaceAll("\\h*\\R+\\h*", " ") replaces the following pattern sequence with a single regular space:

  • \h* - zero or more horizontal whitespace
  • \R+ - one or more line break sequences
  • \h* - zero or more horizontal whitespace

Upvotes: 1

Related Questions