You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求匹配末尾带有换行符(\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. \s covers whitespace characters (like \n, spaces), \S covers 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 \n at 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:29:10