RegEx 匹配返回 null,但在在线检查器中有效

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


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


芜湖不芜
浏览 101回答 1
1回答

慕的地6264312

回答在使用完整脚本和电子邮件正文示例重现您的代码后,我可以看到您的 RegEx 没有问题,但当msgBody格式不正确时就会出现问题。总而言之,您的 RegEx<Name>仅在其前面有Namn\n.作为一种解决方法,我会使用条件三元运算符&nbsp;var studentFullName = msgBody.match(regExp) ? msgBody.match(regExp)[0].toString() : "Not Found";,以避免在以不同格式使用代码时出现类型错误。您的代码段已修改var keywords = {&nbsp; FullName: "Namn"};var msgBody = message.getPlainBody();Logger.log(msgBody); //Seems to show the entire contents of the emailvar regExp;regExp = new RegExp("(?<="+keywords.FullName+"\\n).*", 'g');Logger.log(regExp); //Shows up as /(?<=Namn\n)/g in the log, as expectedvar studentFullName = msgBody.match(regExp) ? msgBody.match(regExp)[0].toString() : "Not Found";参考正则表达式:Javascript
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript