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

多行正则表达式需求:匹配日志中特定起止规则的内容

满足指定匹配条件的正则表达式方案

正则表达式(需启用多行+单行模式)

^\s*}\n^\s*\] at MyClass\.MyMethod.*?^\s*.+New Error Object: \[\n?

各部分规则说明

  • ^\s*}\n:匹配第一行,允许开头有任意空白字符(空格、制表符),仅包含}后接换行符
  • ^\s*\] at MyClass\.MyMethod:匹配第二行开头,允许]前有任意空白,后续固定为 at MyClass.MyMethod(.转义避免匹配任意字符)
  • .*?:非贪婪匹配任意内容(启用单行模式后,.可匹配换行符),确保不会过度匹配到下一个目标段
  • ^\s*.+New Error Object: \[\n?:匹配终止行,允许开头有任意空白,行内容以New Error Object: [结尾,可选换行符

实际使用示例

JavaScript环境

const logText = `  }
]   at MyClass.MyMethod
....
// Lines omitted for brevity
....
Exception: New Error Object: [
 {
   some json
 },
 {
   some more json
 }
]   at MyClass.MyMethod
....
// Lines omitted for brevity
....
Exception: New Error Object: [`;

const regex = /^\s*}\n^\s*\] at MyClass\.MyMethod.*?^\s*.+New Error Object: \[\n?/ms;
const result = logText.replace(regex, ',');
console.log(result);

Python环境

import re

log_text = """  }
]   at MyClass.MyMethod
....
// Lines omitted for brevity
....
Exception: New Error Object: [
 {
   some json
 },
 {
   some more json
 }
]   at MyClass.MyMethod
....
// Lines omitted for brevity
....
Exception: New Error Object: ["""

regex = r'^\s*}\n^\s*\] at MyClass\.MyMethod.*?^\s*.+New Error Object: \[\n?'
result = re.sub(regex, ',', log_text, flags=re.M | re.S)
print(result)

效果说明

运行上述代码后,原文本中符合条件的两段内容会被替换为中文逗号,,实现日志中多个JSON数组的自动拼接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:25:37