Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Scripts match regex

Using google scripts I'm trying to match a string part that always looks like this: *YYYYMMDD;hhmm* for example: *20170701;0900*

I defined this regex:

var regExp = ('(?:\*)(?P<date>\d+)(?:\;)(?P<time>\d+)(?:\*)','gi');

and then call it using:

var datepart = textbody.match(regExp);

However I'm not getting any match, although the same text in https://regex101.com/ works well. Any idea what I'm doing wrong?

like image 723
nubie Avatar asked Jul 16 '17 13:07

nubie


1 Answers

You created a regex for PCRE engine, while in Google Apps scripts, you should use one for JavaScript.

Remove all named capturing groups (they are not supported in JS, i.e. (?P<date>\d+) => (\d+)), use a regex literal (i.e. RegExp("pattern", "gi") => /pattern/gi, but i is not necessary here, only use it if there are letters in the pattern), remove the global modifier to get a match with capturing groups intact.

var rx = /\*(\d+);(\d+)\*/;
var datepart = textbody.match(rx); 
var date, time;
if (datepart) {
    date = datepart[1];
    time = datepart[2];
}

Note that (?:\*) = \* because a non-capturing group is still a consuming pattern (i.e. what it matches is added to the match value). Since you want to get subparts of the regex, you just need to focus on the capturing groups, those (...) parts.

like image 85
Wiktor Stribiżew Avatar answered Oct 20 '22 05:10

Wiktor Stribiżew