How to allow white space in any part of the sequence in a regular expression?

Asked

Viewed 640 times

6

I have a field that accepts at least 12 alphanumeric characters, including 9 numeric characters. But there is a catch, that accepts white space whatever the position.

function validaCampo(sCampo) {
        var filter = /^(?=.*?[a-z])(?=(?:.*?\d){9})[a-z\d]{12,}$/i;
        if (filter.test(sCampo)) {
            return true;
        } else {
            return false;
        }
    }
  • I think putting the \ at the end within the [] should work. var filter = /^(?=.*?[a-z])(?=(?:.*?\d){9})[a-z\d\ ]{12,}$/i;

  • 2

    A hint of improvement: ^(?=[^a-z]*[a-z])(?=(?:\D*\d){9})[a-z\d ]{12,}$ - mainly use \D* (zero or more non-numeric characters) is more efficient than .*?, since .*? generates more possibilities to be tested and when the string is invalid regex takes longer to realize it. Compare, that one takes almost 2000 steps to fail, already that one takes only 52 steps. For small strings it doesn’t make much difference, but if you have a lot of tests and large strings, it might help...

  • @hkotsubo Understood. I will. Thank you!

2 answers

6


Just put a space inside the brackets:

/^(?=.*?[a-z])(?=(?:.*?\d){9})[a-z\d ]{12,}$/i
                                    ^ aqui

Notice that there is a gap between the \d and the ].

The brackets define a character class, that is, they take whatever character is inside them.

In the case, [a-z\d ], means "a letter of a to z, or one \d (digit from 0 to 9), or a space".

  • 1

    Phew! Vlw. With the head exploding already. kkkk

4

Putting the \ at the end within the [] should work.

var filter = /^(?=.*?[a-z])(?=(?:.*?\d){9})[a-z\d\ ]{12,}$/i;
^ # inicio
(?=.*?[a-z]) # procura por caracteres `a` atá `z` pelo menos 1
(?=(?:.*?\d){9}) # procura por 9 digitos 
[a-z\d ]{12,} # tem que ter 12 digitos ou mais entre `a` e `z`  numeros e espaços

$ # fim

Link to online tester

Browser other questions tagged

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