为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

芜湖不芜 2023-03-03 15:18:49
我正在编写一个脚本来从注册电子邮件中提取数据并将它们添加到 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 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)[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这可能是我忽略的完全明显的事情,但在这一点上我有点迷路了,所以任何帮助都将不胜感激。
查看完整描述

1 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

回答

在使用完整脚本电子邮件正文示例重现您的代码后,我可以看到您的 RegEx 没有问题,但当msgBody格式不正确时就会出现问题。总而言之,您的 RegEx<Name>仅在其前面有Namn\n.

作为一种解决方法,我会使用条件三元运算符 var studentFullName = msgBody.match(regExp) ? msgBody.match(regExp)[0].toString() : "Not Found";,以避免在以不同格式使用代码时出现类型错误。

您的代码段已修改

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";

参考

正则表达式:Javascript


查看完整回答
反对 回复 2023-03-03
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信