Reputation: 324
I have 2 regular expressions which work perfectly on regex101, but, on the sheet script, one (REGEX_RANGO) returns false when calling .test, and the other (REGEX_INVIDIDUAL) doesn't work at all.
(Note: I use a cell on the sheet to debug this kind of situation, I don't know if its a better one, if someone knows, please, post it!)
My current regular expressions are:
var REGEX_RANGO = /((?=(\d|\,))(\d{1,3}-\d{1,3})+(?=(\s|\,)))/gm;
var REGEX_INDIVIDUAL = /((?<=,)|(?:^(\d)))[^(,|\-)\n]+((?=,)|(?:\s))/gm;
Why i need both? Well, I have a form, which people can join values and the regular expressions can work on them.
Inputs are like:
*000-005,100,200,250-275,300*
:
*001,002,003,010-015*
:
Hope someone knows how to handle this, thanks. You can find my current attemps here and here.
To be clear: this works ok on regex101, not on Google Sheet, maybe a scope or i need to scape the regular expression?
EDITED:
var REGEX_INDIVIDUAL = /((?<=,)|(?:^(\d)))[^(,|\-)]+(?=($|,))/gm;
var j = numeros_ingresados.match( REGEX_INDIVIDUAL )
SpreadsheetApp.getActiveSheet( ).getRange("F1").setValue( " >> j : " + j )
Upvotes: 2
Views: 4905
Reputation: 626748
Note that GAS JS RegExp
does not support lookbehinds like (?<=,)
in your pattern.
You may use the following sample code to extract the values you need:
function extractRangos() {
var s = "000-005,100,200,250-275,300";
var REGEX_RANGO = /(?:^|,)(\d+)-(\d+)(?![^,])/g;
var REGEX_INDIVIDUAL = /(?:^|,)(\d+)(?![^,])/g;
var m, res_rango = [], res_ind = [];
while (m = REGEX_RANGO.exec(s)) {
res_rango.push(m[1]);
res_rango.push(m[2]);
}
while (m = REGEX_INDIVIDUAL.exec(s)) {
res_ind.push(m[1]);
}
Logger.log(res_rango);
Logger.log(res_ind);
}
Result log:
Regexp details
The individual regex pattern is
(?:^|,)(\d+)(?![^,])
It matches
(?:^|,)
- start of a string or a comma(\d+)
- Capturing group 1: one or more digits(?![^,])
- a negative lookahead that fails the match if the next char is not a comma (the next char after the digits should be a comma or end of string).The point is to collect only Group 1 values.
See its online demo
The rango regex pattern is
(?:^|,)(\d+)-(\d+)(?![^,])
See this online demo
It matches:
(?:^|,)
- a non-capturing group matching the start of string or a comma(\d+)
- Group 1: one or more digits-
- a hyphen(\d+)
- Group 2: one or more digits(?![^,])
- a negative lookahead that fails the match if the next char is not a comma.The point is to collect only Group 1 and 2 values.
Upvotes: 2