developer033 developer033 - 6 months ago 19
Java Question

Remove multiline spaces

First of all, I want to remove the spaces of each line in my text.
The regex that I have now, works, but it's also removing blank lines, which should be maintained.

My regex:

(?m)\s+$


I made a test with negative lookbehind, but it doesn't work.

(?m)(?<!^)\s+$


Sample of text:

This text is styled with some of the text formatting properties.**
**The heading uses the text-align, text-transform, and color*
properties. The paragraph is indented, aligned, and the space*
***************************************************************
*between characters is specified. The underline is removed from*
this colored "Try it Yourself" link.*
***************************************************************


As I said, it should remove only the leading and trailing spaces, but not blank lines.

Caption: (*) - represents a white space.

Answer

To do this with a regular expression, I'd do it in two regular expression calls:

String text = "This text is styled with some of the text formatting properties.  \n"
   + "  The heading uses the text-align, text-transform, and color\n"
   + "\n"
   + "properties. The paragraph is indented, aligned, and the space \n"
   + "     \n";
String result = text.replaceAll("(?m)^\\s+", "").replaceAll("(?m)\\s+$", "");

I wouldn't use a regular expression though. I'd use a split to get each line and then trim. I'm not clear if you want to include blank lines. (Your post says you want them excluded, but your comment says you want them included.) It's just a matter of removing the filter though.

String result = Pattern.compile("\n").splitAsStream(text)
   .map(String::trim)
   .filter(s -> ! s.isEmpty())
   .collect(Collectors.joining("\n"));      

And if you are on Java 7 (add an if statement if you want to exclude blank lines)

String[] lines = text.split("\n");
StringBuilder buffer = new StringBuilder();
for (String line : lines) {
   buffer.append(line.trim());
   buffer.append("\n");
}
String result = buffer.toString();