Match in string does not work with 1 character

3

I have the following obstacle:

var myString = "c/q/1";
var match = myString.match(/c\/q\/([a-zA-Z0-9-].+)/);

But match returns as null , already in the following example:

var myString = "c/q/stringdegrandevalor";
var match = myString.match(/c\/q\/([a-zA-Z0-9-].+)/);

match is returned with the searched value, which leads me to believe that it is the size of the string in numeric expression 1, which is generating this problem, how could I solve it?

    
asked by anonymous 10.06.2018 / 02:34

2 answers

3

Remove the dot . .

With the dot you're saying that after c/q/ must have [a-zA-Z0-9-] and some other character (any), so if you only put 1 character after c/q/ , the default does not set because it would be necessary at least 2 characters (the 1st being in the [a-zA-Z0-9-] pattern) after the last bar / .

According to this documentation , the dot is a metacharacter which means "any character."

With the dot:

                        .
                        ↓
 c/q/1{cadê o caractere aqui exigido pelo ponto?}
     ↑
[a-zA-Z0-9-]

Example:

var myString = "c/q/1";
var match = myString.match(/c\/q\/([a-zA-Z0-9-]+)/);
console.log(match);
    
10.06.2018 / 02:57
3

Let's break the final part of the expression ( [a-zA-Z0-9-].+ ) to better understand:

  • [a-zA-Z0-9-] : means "a letter, number or dash"
  • . : means "any character"
  • + : means "one or more occurrences" of the previous expression
    • that is, .+ means "one or more occurrences of any character"

Therefore, the expression [a-zA-Z0-9-].+ means "the first character can be a letter, number, or dash, and then has one or more occurrences of any character."

That is, this expression is taking at least two characters.

If what you want is "one or more occurrences of letter, number, or dash," you should remove . , and therefore the expression should be [a-zA-Z0-9-]+ .

    
10.06.2018 / 02:56