java - 正则表达式以匹配末尾有新行的文本
问题描述
我正在寻找仅当文本末尾有新行 (\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
推荐阅读
- css - 如何在标签中添加内联样式?
- ios - 如何获取 INTask 的 SiriKit 选择事件?
- javascript - React 在启动时从 api 获取所有数据
- activiti - 不使用 activiti 表时如何将任务分配给候选组?
- server - 如何修复 NoMachine 中的 CAPS LOCK 同步?
- python - 如何从用户那里捕获 3 个点并形成一个三角形?
- amazon-dynamodb - 如何使用 AWS Glue ETL 加载 dynamodb 表
- java - 如何使用 Shell 脚本从 XML 有效负载中提取值
- d3.js - 在 D3 中格式化刻度值
- wordpress - 更改 WordPress 地址