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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With