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

如何用Javascript与RegEx提取指定文本并忽略括号内容及换行?

没问题,我来帮你搞定这个正则提取的需求!你要的就是忽略括号()、方括号[]里的内容和换行,只保留每个字段的有效文本对吧?我给你两种可行的JavaScript方案,都能达到目标:

方案一:用正则匹配分组直接提取

这种方法一步到位,通过正则精准匹配每个字段及其有效内容,同时跳过需要忽略的部分:

const inputText = `Title: (some text) My Title [abc] Content: (some test) My long content paragraph. With multiple sentences. [abc] Short Content: (some text) Short content [abc]`;

// 正则核心:匹配字段名,跳过所有()/[]内容,捕获有效文本
const fieldRegex = /(Title|Content|Short Content):\s*(?:\([^)]*\)\s*)*(?:\[[^\]]*\]\s*)*([\s\S]*?)(?=\s*(?:Title|Content|Short Content):|$)/g;

let output = '';
let matchResult;
// 循环匹配所有字段
while ((matchResult = fieldRegex.exec(inputText)) !== null) {
  const fieldName = matchResult[1];
  // 清理内容里残留的空白和括号内容,再去掉首尾空格
  const cleanContent = matchResult[2]
    .replace(/\s*(?:\([^)]*\)|\[[^\]]*\])\s*/g, '')
    .trim();
  output += `${fieldName}: ${cleanContent}\n`;
}

console.log(output.trim());

正则说明:

  • (Title|Content|Short Content)::精准匹配三个字段名,后面跟冒号
  • \s*:匹配字段名后的任意空白(包括换行、空格)
  • (?:\([^)]*\)\s*)*:非捕获组,匹配任意次数的(...)内容及后面的空白
  • (?:\[[^\]]*\]\s*)*:非捕获组,匹配任意次数的[...]内容及后面的空白
  • ([\s\S]*?):捕获有效文本,[\s\S]匹配所有字符(包括换行),*?非贪婪匹配避免过度捕获
  • (?=\s*(?:Title|Content|Short Content):|$):正向预查,确保匹配到下一个字段开头或者文本结尾就停止

方案二:先预处理文本再分割字段

如果觉得正则太复杂,可以先把所有要忽略的内容批量清理掉,再拆分字段:

const inputText = `Title: (some text) My Title [abc] Content: (some test) My long content paragraph. With multiple sentences. [abc] Short Content: (some text) Short content [abc]`;

// 第一步:批量移除所有()和[]及其内容,再把多余空白(包括换行)换成单个空格
const cleanedRawText = inputText
  .replace(/\([^)]*\)|\[[^\]]*\]/g, '')
  .replace(/\s+/g, ' ')
  .trim();

// 第二步:按字段名分割文本(正向预查确保只在字段名前分割)
const fieldParts = cleanedRawText.split(/\s+(?=(Title|Content|Short Content):)/);

// 拼接成目标格式
let output = '';
for (let i = 0; i < fieldParts.length; i += 2) {
  const fieldName = fieldParts[i].replace(':', '');
  const content = fieldParts[i + 1].trim();
  output += `${fieldName}: ${content}\n`;
}

console.log(output.trim());

这两种方法都能输出你要的结果:

Title: My Title
Content: My long content paragraph. With multiple sentences.
Short Content: Short content

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:14:26