Regular Expression - Only numbers, no space

1

I have the following regular expression ' ((?:[\d][\s]?){5}[\d]) ' and I'm testing it on link .

My problem is this: If I have this snippet ' teste 123456 teste ' it will only return me ' 123456 ' which is correct. But if it is ' teste 12 345 6 teste ' it returns me ' 12 345 6 '.

I would like to know a way for it to return only the numbers without the spaces, if it has spaces.

    
asked by anonymous 23.06.2016 / 19:40

3 answers

3

Remove everything except numbers

"teste 123456 teste".replace(/\D/g, '');   // 123456
"teste 12 345 6 teste".replace(/\D/g, ''); // 123456

Capture all that is number and space, but consider the numbers

var input = "teste 12 345 6 teste"; // string teste
var regex = /(\d+)| /g;             // regex

var matches, output = [];           // vars para processo
while (matches = regex.exec(input)) {  // captura do contudo, o exec vai capturar 
                                       // o primeiro resultado que encontrar seja 
                                       // '\d' ou ' ', quando capturar ' ' não 
                                       // haverá grupo 1, assim ao fazer o 'matches[1]' 
                                       // este estará 'undefined' que no filter é 
                                       // false, assim o eliminando do array.

    output.push(matches[1]);        // adiciona o grupo 1 a out
}
output.filter(function(value){
  return value;                     // limpeza do array
}).join('')                         // concatena tudo por join

Result: 123456

    
23.06.2016 / 21:41
2

If it is exactly for that expression that says in the comment, do so it gives. If you do not boot the possible variables, which agent hits ...

"(\b[0-9]\b)/g"

If it is enough of the ok in the answer, if no one comments that agent hits ...

    
23.06.2016 / 20:06
1

Regular expressions are used to recognize characters within a string. With them you can also get what was the recognized substring.

It occurs that 123456 is not substring of teste 12 345 6 teste . And therefore, you will not be able to get 123456 as a response using only regex in a single step because 123456 is not exactly like this in the input string.

Then you do the following:

  • Use ((?:[\d][\s]?){5}[\d]) to find the number with spaces.
  • Take the spaces later using a replace .
  • 23.06.2016 / 21:39