[英]Regular expression to match a text with new line at the end
我正在尋找僅在文本末尾有換行(\\ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.