4
votes

I'm trying to extract a substring of a email document with a regular expression. I'm testing the regex online, and it works perfectly:

online regex tester

I have a function to check the regex on Google Apps Script and the same regex isn't working here.

var regex = new RegExp("Intrusion signature\(s\)\:\n\n(.*)");
var e = regex.exec(data);

Google Apps Script code

Logger

Does anyone knows why is not working?

2
Maybe because \n\n isn't truly capturing all the spacing present between your expression and the text you want to extract. Try using \s+ instead. - Pedro Corso
Also, when you're instantiating a RegExp object, backslashes must be escaped: var regex = new RegExp("Intrusion signature\\(s\\)\\:\\n\\n(.*)"); - Pedro Corso
I have changed the regex to Intrusion signature(s)\:\s+(.*) and still doesnt work... I think Google Apps Script does not accept this format :( - Juan Bravo Roig

2 Answers

13
votes

Using a literal regex instead of converting the string to a regex works.

var regex = new RegExp(/Intrusion signature\(s\)\:\n\n(.*)/);

enter image description here

0
votes

When you use regular strings with RegExp you need to escape every backslash. Here are some alternatives you can use. Another aspect to consider is that if you have CR+LF in your Spreasheet. In that case you need to change your code to include \r I've added some google API mocked code so that the code snippet can run here

// -----------------  Ignore this (Mock)
Logger=console;
class _SpreadsheetApp { getActiveSpreadsheet() {  class SpreadSheet {    getSheetByName(name) {
 class Sheet { getRange() { class Range { getValue() {
            return "  * Intrusion signature(s):\r\n\r\n      - This is the text I want to extract.\r\n\r\n * SI communication:\r\n";
} } return new Range(); } } return new Sheet(); } } return new SpreadSheet(); } }
var SpreadsheetApp=new _SpreadsheetApp();
// ----------------- Ignore this (Mock)

function checkRegExp() {
  var data=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LOG").getRange("C213").getValue();
  var regex = new RegExp("Intrusion signature\(s\)\:\n\n(.*)");  // ORIGINAL
  var e = regex.exec(data);
  Logger.log("Original:"+e);

  var sol1 = new RegExp("Intrusion signature\\(s\\)\\:\\r\\n\\r\\n(.*)");
  e = sol1.exec(data); 
  if (e) Logger.log("Solution 1:"+e[1]);

  var sol2 = new RegExp("Intrusion signature\\(s\\)\\:\\W{2,4}(.*)");
  e = sol2.exec(data); 
  if (e) Logger.log("Solution 2:"+e[1]);

  var sol3 = new RegExp("Intrusion signature\\(s\\)\\:(?:\\x0d\\x0a)+(.*)");
  e = sol3.exec(data); 
  if (e) Logger.log("Solution 3:"+e[1]);

  var sol4 =   new RegExp(/Intrusion signature\(s\)\:\r\n\r\n(.*)/);
  e = sol4.exec(data); 
  if (e) Logger.log("Solution 4:"+e[1]);
  
}

checkRegExp()