首页 > 解决方案 > 正则表达式以匹配末尾有新行的文本

问题描述

我正在寻找仅当文本末尾有新行 (\n) 时才匹配的正则表达式。不管我有多少行最后一行应该以新行结束。

例如,

TEXT1 = "This is a text without a new line at the end" failed to match
TEXT2 = "This is a text with a new line at the end\n" success to match
TEXT3 = "This is a \n text with multiple lines" failed to match
TEXT4 = "This is a \n text with multiple lines\n a new line at the end\n" success to match

我使用以下正则表达式,但它没有按我预期的那样工作:

^((.)*(\r\n|\r|\n)*)*(\r\n|\r|\n)+$

标签: javaregex

解决方案


你可以用String.endsWith做到这一点:

"abc\n".endsWith("\n")  // true 

或使用Matcher.find

Pattern.compile("\\n$").matcher("abc\n").find();  // true

如果您希望您的正则表达式从头到尾匹配整个字符串,您可以使用Pattern.DOTALL标志来更改点表达式 ( .) 的行为以匹配任何字符,包括换行符。DOTALL 可以使用嵌入标志(?s)或作为Pattern.compile的选项指定:

"abc\n".matches("(?s)^.*\\n$")  // true

Pattern.compile("^.*\\n$", Pattern.DOTALL).matcher("abc\n").matches(); // true

推荐阅读