谷歌表格中的正则表达式正向后视

knu*_*ich 3 regex google-sheets

我有一个包含交易列表的 Google 表格。我需要在 E 列中隔离 D 列中单词“结束”之后的最多三个单词或数字。正确的正则表达式函数应该是正向后视,但在 RE2 中不受支持(来源:使用正-前瞻 (?=regex) 与 re2)。

此公式在 GSheets 中返回错误:

=REGEXEXTRACT(D1;"(?<=end\s)(\w+)")
Run Code Online (Sandbox Code Playgroud)

所以我的结论是,在这种情况下,正则表达式是一个死胡同。

如何在 GSheets 中获取请求的结果?

Wik*_*żew 5

您可以在正则表达式中使用捕获组来REGEXEXTRACT返回捕获的部分:

=REGEXEXTRACT(D1;"end\s*(\w+)")
Run Code Online (Sandbox Code Playgroud)

如果您需要在 后返回 1、2 或 3 个以空格分隔的单词end,请使用

=REGEXEXTRACT(D1;"end\s*(\w+(?:\s+\w+){0,2})")
Run Code Online (Sandbox Code Playgroud)

请参阅在线演示(Golang regex 也使用 RE2)。

细节

  • end —— end
  • \s* - 0+ 个空格
  • (\w+(?:\s+\w+){0,2}) - 捕获组 1:
    • \w+- 1+ 个字字符(字母、数字或_
    • (?:\s+\w+){0,2} - 0、1 或 2 次
      • \s+ - 1+ 个空格
      • \w+ - 1+字字符。


D. *_*ell 5

如果您迫切需要 RE2 之外的不同 RegEx 后端,您可以使用应用程序脚本创建一个使用 JS 来评估 RegEx 的自定义函数。

  1. 单击工具>脚本编辑器
  2. 在编辑器中添加自定义 JS RegEx 函数。您可以使用下面的示例。
  3. 给它起一个名字JS_REGEXEXTRACT是一个不错的选择。
  4. 单击工具栏中的保存按钮。
  5. 返回到其中包含您的工作表的浏览器选项卡,然后替换REGEXEXTRACTJS_REGEXEXTRACT.

您现在有了一个可用的 JS 基础 RegEx 选项。它不会像 RE2 实现那么快,因此在处理具有复杂表达式的大型数据集时要小心。

/**
 * Extracts matching substrings according to a regular expression using JS not RE2.
 *
 * @param {"abcdefg"} text The input text.
 * @param {"c.*f"} regular_expression The first part of `text` that matches this expression will be returned.
 * @return Extracts matching substrings according to a regular expression.
 * @customfunction
 */
function JS_REGEXEXTRACT(text, regular_expression) {
  if (text.length < 1) {
    return null;
  }
  matches = text.match(new RegExp(regular_expression))
  if (matches && matches.length >= 1) {
    return matches[1];
  }
  return matches;
}
Run Code Online (Sandbox Code Playgroud)