英文:
What is the Regular Expression to get all the newline characters from the end of the string
问题
我已经尝试过 [\s]+$ 和 (?:$|\s)+$,但是我没有得到预期的输出。
我正在寻找的是:
String str = "以多个换行符结尾的字符串\n\n\n"
换行符可以是:\n 或 \r 或 \r\n,取决于操作系统,所以我们在这里使用 \s+。
我需要找到字符串末尾的所有换行字符,并且我必须在Java代码中使用它。
英文:
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
答案1
得分: 4
以下是翻译好的部分:
重点在于,在Java中,\\s 默认匹配任何非Unicode空白字符(如果使用 (?U)\\s,则会匹配任何Unicode空白字符)。
您可以使用
String regex = "\\R+$";
String regex = "\\R+\\z";
请参阅正则表达式演示。
如果您需要获取字符串末尾的每个单独换行序列,可以使用
String regex = "\\R(?=\\R*$)";
请参阅此正则表达式演示。
这些模式的含义是
\R+- 一个或多个换行序列$- 在字符串末尾(\\z匹配字符串的最末尾,在这种情况下的效果相同)\R(?=\R*$)- 任何换行序列,后面跟随零个或多个换行序列,直到整个字符串的末尾。
英文:
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 (\zmatches 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论