Search code examples
regexempty-list

Regex remove first empty line


In a string like




z


h




I want to remove all empty values with the regex [\r\n]+$ You can see the example

There is still remaning an empty line on top after the substitution, presumably line 3, according to Match Information section in the example above Any suggestions on how to have this empty value matched as well Thanks


Solution

  • You need to remove all line breaks from the start of the string first.

    The /[\r\n]+$/mg will remove all line breaks, but it stops before the last end of line char of a line break char streak, so all the initial empty lines but the last are removed.

    So, in a PCRE (as well as .NET, Java, Python re, Ruby) pattern, you may use

    \A[\r\n]+|[\r\n]+$
    

    See the regex demo, use it with multiline and global flag in the regex101 tester.

    Details

    • \A[\r\n]+ - start of string and the 1+ CR or/and LF symbols, as many as possible
    • | - or
    • [\r\n]+$ - 1+ CR/LF symbols, as many as possible, followed with a line break or end of string.