regexgoogle-apps-script

My Google Apps script regex requires a match for either one expression or another.


The text being matched will either be an 'Issue' or 'Request' with accompanying text. e.g.

Issue: Inspection on all Boilers

Request: Repair Feed water pump Boiler 5

If I test my expression using a javascript on line regex test utility it works as expected, however my apps script fails as only the first expression is tested and the alternative capturing group is always ignored.

tmp = content.match(/Request\s{0,3}:\s{0,3}([A-Za-z0-9.,'&\s]+)(\r?\n)|Issue\s{0,3}:\s{0,3}([A-Za-z0-9.,'&\s]+)(\r?\n)/);


Solution

  • You may use

    var s = "Issue: Inspection on all Boilers\n\nRequest: Repair Feed water pump Boiler 5";
    var match = s.match(/\b(?:Issue|Request)\s*:\s*(.+)/); // Get a match
    if (match) {                                           // Check if there is a match first
      console.log(match[1]);
    }

    The pattern matches

    We first get a match using String#match method, then check if there is a match with if (match) (or, an error will pop up upon trying to access match[1] if there was no match) and then access the contents of the first and only capturing group using match[1].