1
votes

I have a Google Apps Script I need to extract the IP's, the problem is that they could be in the same line:

enter image description here

or in two lines:

enter image description here

When the IP's are in the same line everything works properly:

    function regtest (){

      //In this cell I have gmail content 
      var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LOG").getRange("C364").getValue();

      var regex = new RegExp(/\- Destination ip address\(es\):(.*)/);
      var e = regex.exec(data);
      Logger.log(e);
    }

But i don't know how to extract the IP's when they are in different lines...

Could someone help me?

1
So, this is a comma-separated list of IPs after a certain string, right? Also, it might span across line breaks? - Wiktor Stribiżew
Exactly, it's a list of IP's separated by comma. The capture group has to capture the data until the next guidon (-) - Juan Bravo Roig

1 Answers

1
votes

I tested against a - Destination ip address(es): 1.2.4.6, 2.2.4.6, 3.2.4.6,\n 4.2.4.6 string:

enter image description here

It appears that the following works:

function regtest (){
  //In this cell I have gmail content 
  var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LOG").getRange("C364").getValue();
  var regex = /- Destination ip address\(es\):((?:\s*,?\s*\d+(?:\.\d+){3})+)/;
  var m, res = [];
  m=regex.exec(data);
  if (m) {
     res = m[1].split(',').map(function (x) { return x.trim(); });
  }
  Logger.log(res);
}

Result:

enter image description here

Basically, the ((?:\s*,?\s*\d+(?:\.\d+){3})+) capturing group matches an optional , enclosed with 0+ whitespaces and then IP-like substrings into 1 group and then all you need is split it with , and strip the resulting items from whitespace.