Regexp to check if input is only integers (int), and check if other numbers are only with two decimal places

I want to know how the regular expression will look for:

  • only integers
  • only numbers with a number less than or equal to two decimal places (23, 23.3, 23.43)
+6
source share
3 answers

Only integers:

/^\d+$/ # explanation \d match a digit + one or more times 

Numbers with no more than two decimal places:

 /^\d+(?:\.\d{1,2})?$/ # explanation \d match a digit... + one or more times ( begin group... ?: but do not capture anything \. match literal dot \d match a digit... {1,2} one or two times ) end group ? make the entire group optional 

Notes:

  • Slashes indicate the beginning and end of a pattern.
  • ^ and $ are the beginning and end of string anchors. Without them, he will look for matches anywhere on the line. So /\d+/ matches '398501' , but also matches 'abc123' . Anchors ensure that the entire string matches the given pattern.
  • If you want to allow negative numbers, add -? before the first \d . Again ? means "zero or once."

Usage example:

 var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/); console.log(rx.test('abc')); // false console.log(rx.test('309')); // true console.log(rx.test('30.9')); // true console.log(rx.test('30.85')); // true console.log(rx.test('30.8573')); // false 
+36
source

I. [1-9][0-9]* if the number must be greater than zero (any series of digits starting with a non-zero digit). if it should be equal to zero or more: (0|[1-9][0-9]*) (zero or nonzero number). If it can be negative: (0|-?[1-9][0-9]*) (zero or nonzero number, which may have a minus sign in front of it.)

II. a regular expression of type I. followed by: (\.[0-9]{1,2})? , which means, optionally, a point followed by one or two digits.

+4
source

Only integers

 /\d+/ 

One or two decimal places:

 /\d(\.\d{1,2})?/ 
+1
source

Source: https://habr.com/ru/post/901574/


All Articles