Regex - Extract a substring of an email document with a regular expression

I'm trying to extract a substring of an 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?


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


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()