String match does not work with 1 character

Asked

Viewed 117 times

3

I have the following obstacle:

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

However 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 value searched, which leads me to believe that is the size of the string in the numerical expression 1, which is generating this problem, as I could solve it?

  • 2

    Try: /c\/q\/([a-zA-Z0-9-]+)/ ... http://jsbin.com/rafemikuba/edit?js,console,output

2 answers

3

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

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

Therefore, the expression [a-zA-Z0-9-].+ means "the first character can be letter, number or stroke, 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 the ., and therefore the expression should be [a-zA-Z0-9-]+.

3


Unsubscribe ..

With the point you’re saying that after c/q/ must have the [a-zA-Z0-9-] and some other character (any one), so if you put only 1 character after the c/q/, the default does not match, because it would take at least 2 characters (1st being the default [a-zA-Z0-9-]) after the last bar /.

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

With the point:

                        .
                        ↓
 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);

Browser other questions tagged

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