Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  173] [ 7]  / answers: 1 / hits: 23153  / 7 Years ago, sun, july 16, 2017, 12:00:00

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?


More From » regex

 Answers
16

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.


[#57064] Thursday, July 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;