简体   繁体   中英

Regex to match if string contains integer/decimal with digits

I want to write a regex that allows an integer number, or a decimal number with 0 - 2 decimal digits.

Valid Input

1
1.
1.1
1.11
111111111
111111111.
111111111.1
111111111.11

Invalid Input

a
a.
1.a
1.111
1.1111
  • string allows any number of digit characters, but only allows 1 decimal/period
  • if a period/decimal exists: only allow 2 digit characters after the decimal

Here is the regex I came up with

\d*\.?([\d]){0,2}

I am having trouble testing it to ensure it works. I found a couple ways of testing it. Using the test method which I just used w3schools setup here . The other way was with some javascript regular expression tester like regexr and regex101 . For all of these: it appears that either my regular expression is returning false positives, or my regular expression does not work as intended.

Question : What regex would do what I want it to do?

  1. You need to make sure that you check the complete string (from the first char to the last char) using ^...$
  2. The first digit should appear at least 1 time (so you want to use + and not * ).

Check this example:

 r = /^\\d+\\.?\\d{0,2}$/ tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111'] tests.forEach(function(val) { console.log(val, val.match(r) ? ': valid' : ': invalid'); }); 

update

Following the comments - if you need a solution for "integer number, or a decimal number with 0 - 2 decimal digits" (like you said in the question, but not like the valid input section), you can use this:

 r = /^\\d+(\\.\\d\\d{0,1})?$/ console.log('1.'.match(r)) tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111'] tests.forEach(function(val) { console.log(val, val.match(r) ? ': valid' : ': invalid'); }); 

Don't forget closing and opening in Regex, many new Regex for get it and they end up unwanted result, everything should between ^ and $, ^ is starting point of the word(digit) boundary and $ is ending point...something like below should help you, try:

'use strict';
var decimal = /^\d+(\.\d\d{0,2})$/, num = 111111111.11;
console.log(decimal.test(num));

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM