python和google应用脚本中regex的区别(后端引擎相关?)

2024-10-01 09:41:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python(3.6,jupyter notebook)和Google app script中尝试了相同的正则表达式,但在app script中似乎“non-capturing group”不起作用。你知道吗

# python script:
import re
text='<a class=""email"" href=""mailto:SOisAwesome@hello.edu"">'
regex='(?:<a class=""email"" href=""mailto:)(.+?@hello\.edu)(?:"">)'
match=re.search(regex,text)
print(match.group(1))
# result is 'SOisAwesome@hello.edu'

// Google app script
function myFunction() {
  string='<a class=""email"" href=""mailto:SOisAwesome@hello.edu"">'
  regex=new RegExp('(?:<a class=""email"" href=""mailto:)(.+?@hello\.edu)(?:"">)')
  Match=regex.exec(string)
  Logger.log(Match[1])
  // result is 'a class=""email"" href=""mailto:SOisAwesome@hello.edu'
}

如果我没弄错的话,googleapp脚本中的正则表达式引擎应该支持非捕获组(参考https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines,我想我应该看看“JavaScript(ECMAScript)”和“Shy groups”?),有人能解释一下我在这里遗漏了什么吗?你知道吗

提前谢谢!你知道吗


Tags: textreapphelloemailmatchgooglegroup
1条回答
网友
1楼 · 发布于 2024-10-01 09:41:37

首先,在GAS regex声明中,需要在\\之前使用.,因为文本反斜杠形成regex转义序列。你知道吗

现在,似乎GAS非捕获组实现有缺陷。

如果在GAS中运行regex并打印Match对象,您将看到

[18-01-26 08:49:07:198 CET] [<a class=""email"" href=""mailto:SOisAwesome@hello.edu"">, 
a class=""email"" href=""mailto:SOisAwesome@hello.edu, "">]

这意味着,非捕获组与跳过第一个字符的第一个捕获组“合并”。你知道吗

这里还有一些实验:

Logger.log(new RegExp("(?:;\\w+):(\\d+)").exec(";er:34")); // = null, expected [;er:34, 34]
Logger.log(new RegExp("(?:e\\w+):(\\d+)").exec(";er:34")); // = null, expected [er:34, 34]
Logger.log(new RegExp("(?:\\w+):(\\d+)").exec(";er:34"));  // =  [er:34, 34], as expected

要解决此问题,可以删除非捕获括号,如\d=(?:\d)。你知道吗

相关问题 更多 >