【问题标题】:Google Apps Script Extracing Capture GroupGoogle Apps 脚本提取捕获组
【发布时间】:2021-04-19 09:06:10
【问题描述】:

出于最小可重复示例的目的,假设我有这个:

const REGEX = new RegExp(/[0-9]{4}\s([a-z]{4})/gi);

function myFunction() {
  let text = "Here is a code: 4343 nmbv can I capture and group it?";
  let match = text.match(REGEX);
  Logger.log(match);
}


...

11:02:39 AM Info    [4343 nmbv]

我希望能够使用捕获组“原子化”匹配。假设我首先想要数字部分。当我尝试添加命名捕获组时失败:

const REGEX = new RegExp(/(?P<number>[0-9]{4})\s([a-z]{4})/gi);

function myFunction() {
  let text = "Here is a code: 4343 nmbv can I capture and group it?";
  let match = text.match(REGEX);
  Logger.log(match);
}

...

"Attempted to execute myFunction, but could not save.

我知道在进行替换时可以按顺序引用匿名捕获组。但是,当我尝试在正则表达式替换的上下文之外引用匿名捕获组时,它可以预见地失败:

const REGEX = new RegExp(/[0-9]{4})\s([a-z]{4})/gi);

function myFunction() {
  let text = "Here is a code: 4343 nmbv can I capture and group it?";
  let match = text.match(REGEX);
  Logger.log(match);
  Logger.log("$1");
}


...

"Attempted to execute myFunction, but could not save."

如何在 Google Apps 脚本中获取捕获组匹配?

【问题讨论】:

  • 您可以使用您的 2 个捕获组对其进行分组。但请注意,您在上一个示例中错过了(,如果您只有一行,则可以省略/g 标志。否则,您必须在拥有全局标志时循环所有匹配项。 const REGEX = new RegExp(/([0-9]{4})\s([a-z]{4})/i);
  • 如果要访问组1,可以使用match[1]查看JavaScript demo

标签: regex google-apps-script


【解决方案1】:

首先,ECMAScript 2018 中命名的捕获组语法不是(?P&lt;number&gt;[0-9]{4}),而是(?&lt;number&gt;[0-9]{4})。你需要

const REGEX = /(?<number>[0-9]{4})\s([a-z]{4})/gi;

然后,为了获得所有匹配项,您需要String#matchAll,它也会保留组。 String#match 省略所有组。

然后,一旦获得匹配项,您需要访问match.groups.&lt;group_name&gt; 以获取命名组值。

你可以使用

function myFunction123() {
  let text = "Here is a code: 4343 nmbv can I capture and group it?";
  let match = text.matchAll(REGEX);
  Logger.log(Array.from(match, x => [x.groups.number, x[1], x[2]]));
}
// => 11:21:45 AM   Info    [[4343, 4343, nmbv]]

请注意,命名的捕获组也接收数字索引。由于(?&lt;number&gt;[0-9]{4}) 是正则表达式中的第一组,它的ID 为1,所以x.groups.number 的值与x[1] 的值相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多