我正在寻找一个仅在文本末尾有换行符 (\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)+$
最佳答案
您可以使用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
关于java - 正则表达式匹配末尾有换行的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082599/