亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號