Reputation: 137
I have an array of numbers from 0 to 10 ["0", "1", ..., "10"] and i'm using text.search(array[i])
where the text contains "10" (This is 10). The code always find "1" but not "10". Can i create a RegExp
to find 10
?
Thanks a lot.
function analizar(text) {
var querer = ["baja", "muestra", "ver", "imprim"];
var tema = ["contenido", "asunto", "materia", "texto", "leccion"];
var temas =[" 0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var keys = [querer, tema, temas];
var resultado = 0;
var str = []
for (var a = 0; a < keys.length; a++){
for (var b = 0; b < keys[a].length; b++){
var actual = keys[a];
var buscar = actual[b];
here is the issue. I don't know how search exact for number 10
if (a == "2") {var buscar = new RegExp(actual[b]);}
var val = text.search (buscar)
if (val > -1) {
resultado++;
if(a == "2") {str.push(keys[a][b])}
break;
}
}
}
Logger.log(str[0]);
if (resultado == 3) {return str[0]}
if (resultado != 3) {return "";}
}
Upvotes: 0
Views: 1406
Reputation: 1182
The first problem is you search low to high through the numbers. This will mean we find 1
and return whereas we should have been greedy and matched the 0
after the 1
to match the full 10
.
So just rearranging your array:
var temas =[ "10", " 0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
should give correct output.
However you are not at all using regexes for their true power. A single regular expression could describe that whole array:
/10?|[2-9]| 0/
Regex breakdown:
10?
: match a character 1
that occurs exactly once followed by 0
either 1 or 0 times. (this captures the 1
case and the 10
case)
|
: This is an OR
operation. Match either the expression to the left or to the right.
[2-9]
: match a single character in the range 2
to 9
|
: another OR
0
: match the character exactly once followed by exactly one
0
character.
Upvotes: 1
Reputation: 3019
The problem ist the order of your regexp strings in the temas
array. Since you are checking the string for 1
and after that for 10
, any string containing 10
will always match 1
. Since you are breaking after you have a match, you will never get to 10
.
You need to move 10
in front of 1
then it will work as expected.
var temas =[" 0", "10", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
Upvotes: 1