Remove spaces between line breaks only

Viewed 90

I have the following example string with line breaks "\n" and spaces " ":

a <- "\n \n \n \nTEST TEST\n"

I would like to remove spaces (" ") directly following after line breaks ("\n"), but not the spaces after other strings (like "TEST" in my toy example). My desired output is therefore:

"\n\n\n\nTEST TEST\n"

I tried stringr's str_remove_all and str_replace_all but didn't succeed as those seem to have problems in this case with the adjacent occurences of the line breaks. This is the closest I got:

str_replace_all(a, "\n[ ]*\n", "\n\n")

I spent hours on this (probably ridiculously easy) problem, any help is thus highly appreciated!

2 Answers
gsub("\n *", "\n", a)

or

str_replace_all(a, "\n *", "\n") # with stringr package

will get you the desired output "\n\n\n\nTEST TEST\n"

EDIT: For space(s) only between blank lines

Note that the above will also remove spaces that appear at the start of non-blank lines—e.g., if the string was "\n TEST TEST \n"

@bobble bubble's suggestion of including (?=\n) into the search pattern (i.e., "\n *(?=\n)") works for between blank lines. (Thank you, bobble bubble)

gsub("\n *(?=\n)", "\n", a, perl=TRUE)

or

str_replace_all(a, "\n *(?=\n)", "\n") # with stringr package

(?=(regex)) is a positive lookahead assertion. As "\n *(?=\n)", it means that the asserted regex \n needs to appear directly after \n * (new line with blank space(s)), but it will not be captured in the string pattern. Because the asserted regex is not captured in the pattern, it does not get replaced when using gsub or stringr::str_replace_all.

To illustrate this more clearly, only the "b" that appears before "bu" is replaced in the following example:

str_replace_all("bobblebbubble", "b(?=bu)", "_")
#[1] "bobble_bubble"

I believe you can remove any line that consists of horizontal whitespace. With stringr, you can use

library(stringr)
a <- "\n \n   \n \nTEST TEST\n"
stringr::str_replace_all(a, "(?m)^\\h+$", "")

See the R demo and the regex demo. Details:

  • (?m) - a multiline modifier making ^ match start of any line and $ match any end of line positions
  • ^ - line start
  • \h+ - one or more horizontal whitespace chars
  • $ - line end.
Related