String containing only numbers

Asked

Viewed 69 times

0

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

"12454853", "12", "9012"

These are valid, but I need when a string like:

"123g123", "123er*"

He calls it invalid.

2 answers

3


You can use this regex:

^[0-9]+$

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

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

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

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

See the regex working 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, the \d may also correspond to other characters representing digits, such as the characters ٠١٢٣٤٥٦٧٨٩ (see this answer for more details).

Since it is not clear what language/engine/configuration you are using, I would say to use [0-9], so you ensure that only digits from 0 to 9 will be accepted.

  • There is another alternative which is to use the native functions of the language you are using to check if the string only has numbers (every language has something of the type, and depending on the case may even be simpler than regex). But anyway, the solution with regex is this... :)

1

See 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");
}

Browser other questions tagged

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