Search code examples
javaregexregex-group

What is the Regular Expression to get all the newline characters from the end of the string


I have tried with [\s]+$ and (?:$|\s)+$ but i don't get the desired output.

What i am looking for is

String str ="this is a string ending with multiple newlines\n\n\n" 

the new line can be : \n or \r or \r\n depending on OS so we use \s+ here.

I need to find all the newline chars from end of the string and i have to use it in Java Code


Solution

  • The point is that \s, in Java, matches any non-Unicode whitespace by default (it matches any Unicode whitespace if you use (?U)\s).

    You can use

    String regex = "\\R+$";
    String regex = "\\R+\\z";
    

    See the regex demo.

    If you need to get each individual line break sequence at the end of string, you can use

    String regex = "\\R(?=\\R*$)";
    

    See this regex demo.

    These patterns mean

    • \R+ - one or more line break sequences
    • $ - at the end of the string (\z matches the very end of string and will work identically in this case)
    • \R(?=\R*$) - any line break sequence followed with zero or more line break sequences up to the end of the whole string.