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

求提取ti,ab嵌套括号内内容的正则表达式及代码适配方案

Extract Nested Parentheses Content for ti,ab(...) in Google Apps Script

First, let's fix the core issue with your original regex: /\((ti,ab.*)\)/ig stops at the first closing parenthesis, which can't handle the nested parentheses in your input. To capture the full nested structure properly, we need a recursive regex pattern that accounts for all levels of nested brackets.

Solution Regex

Here's the corrected regex you need:

/\(ti,ab((?:[^()]|(?R))*)\)/i

Regex Breakdown

  • \(ti,ab: Matches the literal starting sequence (ti,ab
  • (?:[^()]|(?R))*: A non-capturing group that either matches any character that isn't a parenthesis ([^()]) or recursively matches the entire pattern ((?R)), letting us capture all nested parentheses layers
  • \): Matches the final closing parenthesis that wraps the entire ti,ab(...) block
  • i: Case-insensitive flag (works for TI,AB or any case variation)

Updated Google Apps Script Code

Replace your regex line with the corrected one, and fix the minor syntax issue in the if statement to avoid errors:

var messageBody = message.getPlainBody()
var ssFile = DriveApp.getFileById(id);
DriveApp.getFolderById(folder.getId()).addFile(ssFile);
var ss = SpreadsheetApp.open(ssFile);
var sheet = ss.getSheets()[0];
sheet.insertColumnAfter(sheet.getLastColumn());
SpreadsheetApp.flush();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn() + 1)
var values = range.getValues();
values[0][sheet.getLastColumn()] = "Search Strategy";
for (var i = 1; i < values.length; i++) {
  // Corrected Regex here
  var y = messageBody.match(/\(ti,ab((?:[^()]|(?R))*)\)/i);
  if (y) { // Fixed syntax: added braces and proper match check
    // Wrap y[1] with parentheses to match your desired output format
    values[i][values[i].length - 1] = "(" + y[1] + ")";
  } else {
    // Handle cases where no match is found to avoid undefined values
    values[i][values[i].length - 1] = "";
  }
}
range.setValues(values);

Key Notes

  • The match method returns an array: y[0] is the full matched string (e.g., (ti,ab(text(text here...)))), and y[1] is the inner content inside ti,ab(...). We wrap y[1] with parentheses to get your exact desired output.
  • The (?R) recursive pattern is supported in modern JavaScript (and thus Google Apps Script), which correctly handles nested parentheses.
  • The else clause ensures empty cells instead of undefined values when no match exists.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:50:20