使用Google Apps脚本解析电子邮件,正则表达式问题?

时间:2017-05-16 00:26:18

标签: regex parsing google-apps-script gmail

我曾经非常精通使用excel的VBA,但我现在正试图用Google Scripts做一些事情而且我很好并且真的卡住了。

基本上,我试图将标准化电子邮件中的数据从Gmail中提取到Google表格中。到目前为止,我已经咨询过这个主题的其他几个主题,我可以将电子邮件的正文放到表格中但不能解析它。

我是regex的新手,但tests OK on regex101

我也是谷歌脚本的新手,甚至调试器现在似乎已经停止工作了(它之前做过,所以如果有人能说明为什么会这样做,那将不胜感激。)

这是我的基本功能:

function processInboxToSheet() {
  var label = GmailApp.getUserLabelByName("NEWNOPS");
  var threads = label.getThreads();
  // Set destination sheet
  var sheet = SpreadsheetApp.getActiveSheet();
  // Get all emails labelled NEWNOPS 
  for (var i = 0; i < threads.length; i++) {
    var tmp,
      message = threads[i].getMessages()[1],  // second message in thread
      content = message.getPlainBody();  // remove html markup
    if (content) {

      // search email for 'of:' and capure next line of text as address
      // tests OK at regex101.com
      property = content.match(/of:[\n]([^\r\n]*)[\r\n]/); 

      // if no match, display error
      var property = (tmp && tmp[1]) ? tmp[1].trim() : 'No property';
      sheet.appendRow([property]);
    } // End if
  // remove label to avoid duplication 
  threads[i].removeLabel(label)
  } // End for loop
}

我可以将'content'附加到表单Ok,但无法提取正则表达式所需的地址文本。内容显示如下:

  

购买的NOPS:
  123 Any Street,Anytown,AN1 1AN

     

日期:05/05/2017
  价格:241,000英镑

     

卖家的详细信息
  姓名:卖方女士

感谢阅读:)

2 个答案:

答案 0 :(得分:1)

.match()的返回值是一个数组。包含地址的第一个捕获组将位于索引1处。

根据您致电.match()后的以下行,看起来应该为tmp变量分配该数组,而不是property变量。

var property = (tmp && tmp[1]) ? tmp[1].trim() : 'No property';

该行说明,如果.match()返回的内容不为null并且索引为1,则修剪该值并分配给property,否则为其分配字符串&# 39;没有财产&#39;。

所以,请尝试更改此行:

property = content.match(/of:[\n]([^\r\n]*)[\r\n]/);  

对此:

tmp = content.match(/of:[\n]([^\r\n]*)[\r\n]/);

答案 1 :(得分:0)

谢谢Kevin,我想我必须在调试时更改它。

问题出在我的regexp上。经过一些试验和错误后,以下工作:

tmp = content.match(/of:[\r\n]+([^\r\n]+)/);