console.log(rule);
// rule = max18
// rule = max120
// rule = max6
var pattMax = new RegExp('^(max).(\d{1,3})');
pattMax.test(rule); //false?
if(pattMax.test(rule)){
console.log('é max seguido de 1 á 3 digitos');
}
console.log(rule);
// rule = max18
// rule = max120
// rule = max6
var pattMax = new RegExp('^(max).(\d{1,3})');
pattMax.test(rule); //false?
if(pattMax.test(rule)){
console.log('é max seguido de 1 á 3 digitos');
}
You were almost there. You must escape \d
to \d
within the RegExp constructor. Otherwise it is "forgotten". Notice here how the bar disappears:
console.log(new RegExp('^(max).(\d{1,3})'));
If you did regex so var pattMax = /'^(max).(\d{1,3})/;
your code would almost work:
var pattMax = /^(max).(\d{1,3})/;
['max18', 'max120', 'max6'].forEach(function(rule) {
console.log(pattMax.test(rule) ? 'é max seguido de 1 á 3 digitos' : 'Falhou!');
});
What fails is that it expects max
plus any character except new line (the .
) and then numbers in the amount of 1 to 3, now it fails.
I think you could just use this: /^max\d{1,3}/
without constructor:
var pattMax = /^max\d{1,3}/;
['max18', 'max120', 'max6'].forEach(function(rule) {
console.log(pattMax.test(rule) ? 'é max seguido de 1 á 3 digitos' : 'Falhou!');
});
You need to escape the \d
or pass the argument i
to the regex constructor.
var pattMax = new RegExp('^(max)(\d{1,3})', 'i');
pattMax.test(rule); //false?
if(pattMax.test(rule)){
console.log('é max seguido de 1 á 3 digitos');
}
Based on: javascript new regexp from string
In theory, ^max\d{1,3}
The point in your original RegEx takes other characters, such as max_121.
Max120 would work for the wrong reason, the point would get 1, and /d{1,3}
would get 20.
Describing your query :
^(max).(\d{1,3})
^ marca decomeço da linha
( ) ( ) grupos de retorno
max literal "max"
. qualquer caractere, mas tem que ter algum
\d{1,3} de um a três dígitos
Proposed version
^max\d{1,3}
^ começo da linha
max literal "max"
\d{1,3} de um a três digitos
Depending on usage, you can omit ^
(start of line), or even add $
at the end (end of line) if you are going to operate on larger strings and do not want to accept substrings.