String containing numbers only

0

I need a regular expression for a string to receive only numbers, for example:

"12454853", "12", "9012"

These are valid, but I need them when a string appears as:

"123g123", "123er*"

Give it as invalid.

    
asked by anonymous 26.10.2018 / 19:41

2 answers

3

You can use this regex:

^[0-9]+$

The ^ and $ markers respectively indicate the beginning and end of the string. This guarantees that the string will only have, from start to end, what is specified between ^ and $ .

Brackets ( [] ) indicate a character class : they serve to indicate that you want any character that is inside them. In the case I used 0-9 , which means "the digits 0 to 9". Therefore, [0-9] accepts any digit from 0 to 9.

The quantifier + means "one or more occurrences" of what is immediately before it. In this case, [0-9]+ means "one or more digits from 0 to 9".

That is, this regex checks for one or more digits, from start to end of the string. If it has any other character, it fails.

See the regex running here .

For the digits you can also use the shortcut \d , which is equivalent to [0-9] then the regex would be:

^\d+$

The only detail is that depending on the language / engine / configuration, \d can also match other characters representing digits , such as ٠١٢٣٤٥٦٧٨٩ characters (see this answer for more details).

As it is not clear which language / engine / configuration you are using, I would say to use [0-9] , so you guarantee that only the digits 0 through 9 will be accepted.

    
26.10.2018 / 19:53
1

See the regex in the code below:

var regex = /[0-9]/g;

var valor1 = "12312312";
var valor2 = "asdfad";


if(regex.test(valor1)){
  console.log("valor válido");
}else {
  console.log("valor inválido");
}


if(regex.test(valor2)){
  console.log("valor válido");
}else {
  console.log("valor inválido");
}
    
26.10.2018 / 19:50