获取字符串末尾所有换行符的正则表达式是什么。

huangapple go评论66阅读模式
英文:

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 (\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.

huangapple
  • 本文由 发表于 2020年9月24日 02:35:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64034295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定