regex Return false?

Asked

Viewed 68 times

6

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');
}
  • To simplify this regex there, you should always marry max1, max12 or max123? will use the groups p something?

  • no, how would it look? but this is not going through and when I test on sites how regexr works.

  • In theory, enough ^max\d{1,3} - the dot would take other characters, like max_121. Max120 would work for the wrong reason, the dot would take 1, and the /d{1,3} would take the 20

3 answers

7

You need to escape the \d or pass the argument i in the regex builder.

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

6


You were almost there. You must escape \d for \\d inside the Regexp constructor. Otherwise it is "forgotten". Notice here how the bar disappears:

console.log(new RegExp('^(max).(\d{1,3})'));

If you did the regex like this 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 he waits max plus any character except new line (the .) and then numbers in the amount of 1 to 3.

I think you could use it just like this: /^max\d{1,3}/ construction-free:

var pattMax = /^max\d{1,3}/;
['max18', 'max120', 'max6'].forEach(function(rule) {
    console.log(pattMax.test(rule) ? 'é max seguido de 1 á 3 digitos' : 'Falhou!');
});

5

In theory, enough ^max\d{1,3}

The dot in your original Regex takes other characters, like max_121.

Max120 would work for the wrong reason, the point would take the 1, and the /d{1,3} would take the 20.

Describing his 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 the use, you can omit the ^ (line start), or even add $ end (end of line) if you will operate on larger strings and do not want to accept substrings.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.