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

如何适配正则表达式匹配多行内容直至指定模式?

正则匹配解决方案

修改后的正则表达式

(Action type:[\s\S]+?(?=\nNumber Name Degree)|\b[0-9]{8,12}[\s\S]+?(?=\n[0-9]{8,12}|\Z))

必备修饰符:全局匹配修饰符g(需匹配所有符合条件内容时添加),无需额外开启单行模式,[\s\S]已能匹配包含换行在内的所有字符。

正则各部分作用拆解

匹配Action type:开头的多行内容

  • Action type::精准匹配起始标识
  • [\s\S]+?:匹配任意字符(含换行),+?采用非贪婪模式,避免过度匹配后续内容
  • (?=\nNumber Name Degree):正向预查规则,当检测到换行后紧跟Number Name Degree的行时停止匹配,不会包含该行

匹配数字开头的多行条目

  • \b[0-9]{8,12}:匹配8-12位独立数字开头,\b确保数字是完整的起始标识(避免数字属于其他字符串的一部分)
  • [\s\S]+?:匹配任意字符(含换行),非贪婪模式保证匹配范围不超出当前条目
  • (?=\n[0-9]{8,12}|\Z):正向预查规则,遇到下一个数字开头的行或文本结尾\Z时停止,确保每个数字条目独立匹配

示例验证

假设输入文本如下:

Action type: User Modification
This is a multi-line description
covering multiple lines of details
Number Name Degree
123456789012 John Doe Bachelor
This entry has multiple lines
explaining the user's info
987654321098 Jane Smith Master
Another multi-line entry here

使用上述正则会得到3个匹配结果:

  1. Action type: User Modification\nThis is a multi-line description\ncovering multiple lines of details
  2. 123456789012 John Doe Bachelor\nThis entry has multiple lines\nexplaining the user's info
  3. 987654321098 Jane Smith Master\nAnother multi-line entry here

补充说明

  • 若正则引擎支持单行模式(s修饰符),可将[\s\S]替换为.,正则可改写为:
    (Action type:.+?(?=\nNumber Name Degree)|\b[0-9]{8,12}.+?(?=\n[0-9]{8,12}|\Z))
    
    此时需同时添加s和g修饰符。
  • 不同编程语言中修饰符写法有差异:Python需在正则后加flags=re.DOTALL | re.MULTILINE;JavaScript需在正则末尾加/gs。

内容的提问来源于stack exchange,提问作者Itamar Rocha Filho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:35:24