求提取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 entireti,ab(...)blocki: Case-insensitive flag (works forTI,ABor 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
matchmethod returns an array:y[0]is the full matched string (e.g.,(ti,ab(text(text here...)))), andy[1]is the inner content insideti,ab(...). We wrapy[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
elseclause ensures empty cells instead of undefined values when no match exists.
内容的提问来源于stack exchange,提问作者Moka
相关产品推荐
相关产品推荐

