47

I thought that wasn't that hard to do, but I want to remove all empty lines (or lines just containing blanks and tabs in Java) with String.replaceAll.

My regex looks like this:

s = s.replaceAll ("^[ |\t]*\n$", "");

But it doesn't work.

I looked around, but only found regexes for removing empty lines without blanks or tabs.

8 Answers 8

98

Try this:

String text = "line 1\n\nline 3\n\n\nline 5";
String adjusted = text.replaceAll("(?m)^[ \t]*\r?\n", "");
// ...

Note that the regex [ |\t] matches a space, a tab or a pipe char!

EDIT

B.t.w., the regex (?m)^\s+$ would also do the trick.

5
  • 1
    @Val, (?m), not (m?), enables multi line mode. Checkout this link for details: regular-expressions.info/modifiers.html
    – Bart Kiers
    Oct 23, 2013 at 19:29
  • 4
    Regarding the edit's solution: The line-end match ($) should be removed if you wish to remove the blank line itself. Otherwise, the regex will only remove any white-space characters within the line, while still leaving the line there. Dec 4, 2013 at 18:33
  • The example does not correctly escape the \ in Java Strings. You actually need to double escape them like this: (?m)^[ \\t]*\\r?\\n. BTW a shorter expression is: (?m)^\\s*\\n.
    – gucce
    Apr 13, 2017 at 13:53
  • 3
    @gucce "The example does not correctly escape the \ in Java Strings" that is because there is no need to escape \ here and it was purposely used that way. \t in string literal represents tabulator character which is passed to regex engine, who has no problems with it since it is character like any other. Regex allows us to use forms like \\t or \\n or \\r (since some IDEs automatically add escaping to \ making it \\ when we copy-paste it to our code) but this doesn't mean it is preferred over \t \n or \r.
    – Pshemo
    May 20, 2017 at 13:30
  • text.replaceAll("(?m)^\\s+$", "").replaceAll("(?m)^\\n", "") did what I wanted. First it removes the whitespace in whitespace-only lines. Then it removes the empty lines. Sep 16, 2022 at 15:02
9

I don't know the syntax for regular expressions in Java, but /^\s*$[\n\r]{1,}/gm is the regex you're looking for.

You probably write it like this in Java:

s = s.replaceAll("(?m)^\\s*$[\n\r]{1,}", "");

I tested it with JavaScript and it works fine.

7
  • 1
    besides that you need to write \\s in java, this does not work :(
    – reox
    Nov 8, 2010 at 11:49
  • See the edit. Also consider using \s instead of a custom class defined by you and also checking for \n, \r or both as line delimiters. Nov 8, 2010 at 11:51
  • You may wish to look into the compilation options: Pattern.UNIX_LINES, Pattern.DOTALL, and Pattern.MULTILINE.
    – tchrist
    Nov 8, 2010 at 12:14
  • @Alin Purcaru, technically speaking, things like \n are not line delimiters, but rather line terminators. The string :foo:bar: has 2 fields if colon-delimited, 3 fields if colon-terminated, and 4 fields if colon-separated. This does make a difference.
    – tchrist
    Nov 8, 2010 at 14:27
  • @tchrist By your convention I should have called them line-separators, but I considered separator and delimiter synonyms. While separator describes what \n is a little better I don't this is an issue significant enough to worth discussing. Also I can't edit my comment. Nov 8, 2010 at 14:39
5

I'm not a day-to-day Java programmer, so I'm surprised there isn't a simpler way to do this in the JDK than a regex.

Anyway,

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

would be a bit simpler.

Update:

Sorry I missed that you wanted to also remove spaces and tabs.

s = s.replaceAll("\n[ \t]*\n", "\n");

Would work if you have consistent newlines. If not, you may want to consider making them consistent. E.g.:

s = s.replaceAll("[\n\r]+", "\n");
s = s.replaceAll("\n[ \t]*\n", "\n");
2
  • this will not work for lines containing whitespaces or tabs too and of course not for CRLF and LF lineendings
    – reox
    May 12, 2015 at 6:41
  • Ah, sorry. I was assuming consistent line-endings and missed that you wanted spaces and tabs removed.
    – morganwahl
    May 12, 2015 at 14:49
4

You can remove empty lines from your code using the following code:

String test = plainTextWithEmptyLines.replaceAll("[\\\r\\\n]+","");

Here, plainTextWithEmptyLines denotes the string having the empty lines. [\\\r\\\n] is the regex pattern which is used to identify empty line breaks.

3

Bart Kiers's answer is missing the edge case where the last line of the string is empty or contains whitespaces.

If you try

String text = "line 1\n\nline 3\n\n\nline 5\n "; // <-- Mind the \n plus space at the end!
String adjusted = text.replaceAll("(?m)^[ \t]*\r?\n", "");

you'll get a String that equals this

"line 1\nline 3\nline 5\n " // <-- MIND the \n plus space at the end!

as result.

I expanded Bart Kiers' answer to also cover this case.

My regex pattern is:

String pattern = "(?m)^\\s*\\r?\\n|\\r?\\n\\s*(?!.*\\r?\\n)";

A little explanation:

The first part of the pattern is basically the same as Bart Kiers'. It is fine, but it does not remove an "empty" last line or a last line containing whitespaces.

That is because a last line containing just whitespaces does not end with \\r?\\n and would therefore not be matched/replaced. We need something to express this edge case. That's where the second part (after the |) comes in.

It uses a regular expression speciality: negative lookahead. That's the (?!.*\\r?\\n) part of the pattern. (?! marks the beginning of the lookahead. You could read it as: Match the regular expression before the lookahead if it is not followed by whatever is defined as string that must not follow. In our case: not any character (zero or more times) followed by a carriage-return (0 or 1 times) and a newline: .*\\r?\\n. The ) closes the lookahead. The lookahead itself is not part of the match.

If I execute the following code snippet:

String pattern = "(?m)^\\s*\\r?\\n|\\r?\\n\\s*(?!.*\\r?\\n)";
String replacement = "";
String inputString =
        "\n" +
        "Line  2 - above line is empty without spaces\n" +
        "Line  3 - next is empty without whitespaces\n" +
        "\n" +
        "Line  5 - next line is with whitespaces\n" +
        "        \n" +
        "Line  7 - next 2 lines are \"empty\". First one with whitespaces.\n" +
        "        \r\n" +
        "\n" +
        "Line 10 - 3 empty lines follow. The 2nd one with whitespaces in it. One whitespace at the end of this line " +
        "\n" +
        "          \n" +
        "\n";

String ajdustedString = inputString.replaceAll(pattern, replacement);
System.out.println("inputString:");
System.out.println("+----");
System.out.println(inputString);
System.out.println("----+");
System.out.println("ajdustedString:");
System.out.println("+----");
System.out.print(ajdustedString); //MIND the "print" instead of "println"
System.out.println("|EOS"); //String to clearly mark the _E_nd _O_f the adjusted_S_tring
System.out.println("----+");

I get:

inputString:
+----

Line  2 - above line is empty without spaces
Line  3 - next is empty without whitespaces

Line  5 - next line is with whitespaces

Line  7 - next 2 lines are "empty". First one with whitespaces.


Line 10 - 3 empty lines follow. The 2nd one with whitespaces in it. One whitespace at the end of this line



----+
ajdustedString:
+----
Line  2 - above line is empty without spaces
Line  3 - next is empty without whitespaces
Line  5 - next line is with whitespaces
Line  7 - next 2 lines are "empty". First one with whitespaces.
Line 10 - 3 empty lines follow. The 2nd one with whitespaces in it. One whitespace at the end of this line |EOS
----+

If you want to learn more about lookahead/lookbehind see Regex Tutorial - Lookahead and Lookbehind Zero-Length Assertions:

1
  • This was a good solution for me but I changed one small thing as it merged some lines together in my case \\s becomes [ \t]. I don't write in Java but this what RegexBuddy has giving for Java 8, String resultString = subjectString.replaceAll("(?m)^\\s*\r?\n|\r?\n[ \t]*(?!.*\r?\n)", "");
    – Ste
    Aug 3, 2020 at 14:03
2

If want to remove the lines from Microsoft Office, Windows or an text editor which supports regular expression rendering:

 1. Press <kbd>Ctrl</kbd> + <kbd>F</kbd>.
 2. Check the regular expression checkbox
 3. Enter Expression ^\s*\n into the find box as it is.

You will see all you black spaces into your editor disappears...

2
  • Just searching for a regex doesn't make blank spaces disappear, does it? Nonetheless, this regex is probably all OP needs. Checking for tabs, returns is not necessary with \s as they are included in Java and matching multiple lines is useless if you are using replaceAll(). You have my vote. Sep 16, 2014 at 6:12
  • Although you should probably edit the answer to say that. And make it about String as that is what the question asks for specifically. Sep 16, 2014 at 6:14
1

I have some code without using regexp, just import org.apache.commons.lang3.StringUtils;

  File temporaire = new File("temp.txt");
  try {
    Scanner scanner = new Scanner(yourfile);
    BufferedWriter bw = new BufferedWriter(new FileWriter(temporaire));
    while (scanner.hasNextLine()) {
      String line = StringUtils.stripEnd(scanner.nextLine(),null); // Clean blanks at the end of the line
      if (StringUtils.isNotBlank(line)) {
        bw.write(line); // Keep the line only if not blank
        if (scanner.hasNextLine()){
          // Go to next line (Win,Mac,Unix) if there is one
          bw.write(System.getProperty("line.separator"));
        }
      }
      bw.flush();
    }
    scanner.close();
    bw.close();
    fichier.delete();
    temporaire.renameTo(fichier);
  }
  catch (FileNotFoundException e) {
    System.out.println(e.getMessage());
  }
  catch (IOException e) {
    System.out.println(e.getMessage());
  }
}
0

this method remove only empty lines by java:

private String removeEmptyLines(String text) {
    final String[] strings = text.split("\n");
    StringBuilder result = new StringBuilder();
    for (int i = 0, stringsLength = strings.length; i < stringsLength; i++) {
        String str = strings[i];
        if (str.isEmpty()) continue;
        result.append(str);
        if (i + 1 == stringsLength) continue;
        result.append("\n");
    }
    return result.toString();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.