求匹配末尾带有换行符(\n)的文本的正则表达式
Regex to Match Text Ending with a Newline
Here's how you can create a regex that only matches text if it ends with a newline character (\n):
The Regex Pattern
Use this pattern to cover all cases, including multi-line text:
^[\s\S]*\n$
Breakdown:
^: Anchors the match to the start of the string.[\s\S]*: Matches any character (including newlines) zero or more times.\scovers whitespace characters (like\n, spaces),\Scovers non-whitespace, so together they match everything.\n: Explicitly matches the newline character at the end.$: Anchors the match to the end of the string, ensuring the newline is the last character.
Alternative (with DOTALL flag):
If your regex engine supports the DOTALL flag (which makes . match newlines), you can use this simpler pattern:
^.*\n$
Just remember to enable the DOTALL flag (e.g., in Python: re.match(r'^.*\n$', text, re.DOTALL); in JavaScript: /^.*\n$/s).
Testing Your Examples
Let's verify with your sample texts:
- TEXT1:
"This is a text without a new line at the end"→ Fails (no\nat the end) - TEXT2:
"This is a text with a new line at the end\n"→ Passes (ends with\n) - TEXT3:
"This is a \n text with multiple lines"→ Fails (last character is not\n) - TEXT4:
"This is a \n text with multiple lines\n a new line at the end\n"→ Passes (ends with\n)
This regex will correctly identify whether the text ends with a newline, regardless of how many lines are in the middle.
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

