java - 正则表达式匹配末尾有换行的文本

标签 java regex

我正在寻找一个仅在文本末尾有换行符 (\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/

相关文章:

javascript - 如何将所有出现的已知文本包装在 HTML 文档中?

regex - 如何使用 grep 匹配空格或换行符

java - Eclipse - 如何为 Java 控制台提供无限长度(# 行)

java - 生菜中的 RedisCommandTimeoutException 过多

ruby - 如何检查字符串是否仅包含 Ruby 中的空格和字母?

javascript - 在 Javascript 中对 RegEx 运行 RegEx 替换

java - Netflow 记录无法获取八位字节 (jnca)

java - 有没有办法确认线程在执行结束时是否被杀死?

java - 将Java连接到MySQL数据库