无法从Google Apps脚本中的null RegEx错误中读取属性

时间:2017-02-01 19:48:51

标签: regex google-apps-script

我从其他系统(Bananatag)收到自动发送的电子邮件,并尝试创建Google Apps ScriptGAS)以从电子邮件中提取特定信息。我已经开始创建以下代码:

function fieldExtract(){
  var threads = GmailApp.search('from:noreply@bananatag.com');
  for(var m in threads){
  var messages = threads[m].getMessages(),
      tid = threads[m].getId();
  for(var b in messages){
      var body = messages[b].getPlainBody(),
          subj = messages[b].getSubject();
      var CountryExpression = new RegExp("[\n\r].*Country:\s(.*)","g");
      var RegionExpression = new RegExp("[\n\r].*Region:\s(.*)","g"),
          CityExpression = new RegExp("[\n\r].*City:\s(.*)","g"),
          OSExpression = new RegExp("[\n\r].*OS:\s(.*)","g"),
          DeviceExpression = new RegExp("[\n\r].*Device:\s(.*)","g"),
          ClientExpression = new RegExp("[\n\r].*Client:\s(.*)","g"),
          subjExpression = new RegExp("'\s*(.*?)\s*'","g");
      var subject = subjExpression.exec(subj);
      var country = CountryExpression.exec(body)[1];
    }
  }
}

电子邮件正文包含以下信息:

Email Open Notification

-----------------------------------------------
EMAIL DETAILS
-----------------------------------------------
Subject: Re: FW: Payment confirmation: Invoice 1540
Sent at: Tue 17 Jan 2017 03:27:27 PM MST

RECIPIENTS:

Name: {name}
Email: {email}
-----------------------------------------------


View full details at:
https://member.bananatag.com/tag/xxxxxxx

-----------------------------------------------
OPEN DETAILS
-----------------------------------------------
LOCATION:
Country: United States
Region: WA
City: Unknown

ADDITIONAL INFORMATION:
OS: Windows 8
Device: Desktop
Browser/Client: Outlook 2010
Ok

当我在regex101等测试网站上测试RegEx时,它会正确找到我想要的文字。但是,当我在GAS中运行它时会抛出此错误:

  

TypeError:无法读取属性" 1"从null。 (第44行,文件"电子邮件管理")

第44行是这一行var country = CountryExpression.exec(body)[1];

如果我不让[1]country设置为null。为什么GAS在肯定存在时找不到匹配的文本?

我如何使这项工作?

更新

我将代码更改为:

var CountryExpression = /[\n\r].*Country:\s(.*)/g; 

现在可以使用了

0 个答案:

没有答案