【问题标题】:RegEx match returns null, but works in online checker正则表达式匹配返回 null,但适用于在线检查器
【发布时间】:2020-09-15 12:13:40
【问题描述】:

我正在编写一个脚本来从注册电子邮件中提取数据并将它们添加到 Google 表格中。该脚本基于此项目:https://gist.github.com/MoayadAbuRmilah/5835369fdebbecf980029f7339e4d769
我想提取特定标题下的文本,例如“Namn”、“Läsår”、“Personnummer”等,但我使用的 RegEx 公式不会返回任何匹配项,即使它们无论如何都应该有效。
这是一个代码 sn-p,它应该提取“Namn”的第一个实例下的行:

var keywords = {
  FullName: "Namn"
};

var msgBody = message.getPlainBody();
Logger.log(msgBody); //Seems to show the entire contents of the email
var regExp;

regExp = new RegExp("(?<="+keywords.FullName+"\\n).*", 'g');
Logger.log(regExp); //Shows up as /(?<=Namn\n)/g in the log, as expected

var studentFullName = msgBody.match(regExp)[0].toString(); //Should return the line under the first 'Namn' heading, but doesn't

但是,代码在最后一行失败并出现此错误:

TypeError: Cannot read property '0' of null
    at parseNewApplication(Kod:89:57)
    at extractContents(Kod:28:16)
    at importApplications(Kod:14:7)

这是一个示例电子邮件正文(已编辑个人详细信息):https://pastebin.com/EXLt2it2
这是完整的脚本:https://pastebin.com/X2FFRU6K

这可能是我忽略的完全明显的事情,但在这一点上我有点迷茫,所以任何帮助将不胜感激。

【问题讨论】:

    标签: javascript regex google-apps-script


    【解决方案1】:

    回答

    使用完整脚本电子邮件正文示例复制您的代码后,我可以看到您的正则表达式没有问题,当msgBody 没有所需的格式时,问题就会出现。总而言之,您的 RegEx 仅在 Namn\n 开头时才匹配 &lt;Name&gt;

    作为一种解决方法,我会使用 Conditional ternary operator var studentFullName = msgBody.match(regExp) ? msgBody.match(regExp)[0].toString() : "Not Found"; 以避免在以不同格式使用代码时出现 TypeErrors。

    您的 sn-p 已修改

    var keywords = {
      FullName: "Namn"
    };
    
    var msgBody = message.getPlainBody();
    Logger.log(msgBody); //Seems to show the entire contents of the email
    var regExp;
    
    regExp = new RegExp("(?<="+keywords.FullName+"\\n).*", 'g');
    Logger.log(regExp); //Shows up as /(?<=Namn\n)/g in the log, as expected
    
    var studentFullName = msgBody.match(regExp) ? msgBody.match(regExp)[0].toString() : "Not Found";
    

    参考

    Regular Expression: Javascript

    【讨论】:

    • 谢谢,这绝对是一种更优雅的方式来处理不正确的格式,但不幸的是它并没有解决我原来的问题。我想搜索一个关键字(例如“Namn”,在这种情况下),然后匹配下一行的任何内容(在这种情况下它应该匹配 )。关于如何做到这一点的任何提示?
    • 我在您的示例中复制了一封电子邮件。您提供的代码与e-mail example 一起按预期工作并返回,。可能在您的代码的某个时刻,在检索文本时消息为空,或者其中没有“Namn”。正如我提到的,它是关于消息内容的。
    • 好吧,事实证明我们都是对的;无论出于何种原因,电子邮件都使用 Windows/DOS 换行符,即在换行符 (\n) 之前使用回车符 (\r)。每当我将电子邮件粘贴到 RegExr 或 Pastebin 时,回车符一定已被删除,这就是您从未遇到此问题的原因。我使用 string.replace 删除了多余的字符,现在一切正常。
    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 2017-09-06
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多