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

JavaScript正则匹配连续以'-'开头的多行文本块

匹配连续以'-'开头的行块

问题分析

你之前的正则 /^(-.*\n-.*|$)/gm 仅能匹配偶数个列表项,核心原因是它硬编码了"匹配两行"的逻辑(-.*\n-.*),无法适配任意数量的连续行。

正确正则表达式

使用以下正则可以匹配任意数量的连续以'-'开头的行块:

const regex = /^(- .*(?:\n|$))+/gm;

规则解释

  • ^:结合 m 标志,匹配每一行的开头位置。
  • - .*:匹配以'-'开头的单行内容(.* 匹配该行剩余所有字符)。
  • (?:\n|$):非捕获组,匹配行尾的换行符或文本结束位置,确保捕获完整的行。
  • +:匹配前面的子表达式一次或多次,实现连续多行的匹配。
  • gm 标志:g 表示全局匹配所有符合条件的块;m 表示多行模式,让 ^ 和 $ 作用于每一行而非整个文本。

实际使用示例

const text = `some text
- list
- list
- list
more text
- another list
- another list
- another list`;

const matches = text.match(regex);
console.log(matches);
// 输出结果:
// [
//   "- list\n- list\n- list\n",
//   "- another list\n- another list\n- another list"
// ]

内容的提问来源于stack exchange,提问作者john

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 06:42:15