I'm currently using the pattern: \b\d+\b, testing it with these entries:
numb3r 2 3454 3.214 test I only want it to catch 2, and 3454. It works great for catching number words, except that the boundary flags (\b) include "." as consideration as a separate word. I tried excluding the period, but had troubles writing the pattern.
Basically I want to remove integer words, and just them alone.
110 Answers
All you want is the below regex:
^\d+$ 3Similar to manojlds but includes the optional negative/positive numbers:
var regex = /^[-+]?\d+$/; EDIT
If you don't want to allow zeros in the front (023 becomes invalid), you could write it this way:
var regex = /^[-+]?[1-9]\d*$/; EDIT 2
As @DmitriyLezhnev pointed out, if you want to allow the number 0 to be valid by itself but still invalid when in front of other numbers (example: 0 is valid, but 023 is invalid). Then you could use
var regex = /^([+-]?[1-9]\d*|0)$/ 3You could use lookaround instead if all you want to match is whitespace:
(?<=\s|^)\d+(?=\s|$) 3This just allow positive integers.
^[0-9]*[1-9][0-9]*$ I would add this as a comment to the other good answers, but I need more reputation to do so. Be sure to allow for scientific notation if necessary, i.e. 3e4 = 30000. This is default behavior in many languages. I found the following regex to work:
/^[-+]?\d+([Ee][+-]?\d+)?$/; // ^^ If 'e' is present to denote exp notation, get it // ^^^^^ along with optional sign of exponent // ^^^ and the exponent itself // ^ ^^ The entire exponent expression is optional This solution matches integers:
- Negative integers are matched (-1,-2,etc)
- Single zeroes are matched (0)
- Negative zeroes are not (-0, -01, -02)
- Empty spaces are not matched ('')
/^(0|-*[1-9]+[0-9]*)$/ ^([+-]?[0-9]\d*|0)$ will accept numbers with leading "+", leading "-" and leadings "0"
Try /^(?:-?[1-9]\d*$)|(?:^0)$/.
It matches positive, negative numbers as well as zeros.
It doesn't match input like 00, -0, +0, -00, +00, 01.
^(-+)?[1-9][0-9]*$ starts with a - or + for 0 or 1 times, then you want a non zero number (because there is not such a thing -0 or +0) and then it continues with any number from 0 to 9
This worked in my case where I needed positive and negative integers that should NOT include zero-starting numbers like 01258 but should of course include 0
^(-?[1-9]+\d*)$|^0$ Example of valid values: "3", "-3", "0", "-555", "945465464654"
Example of not valid values: "0.0", "1.0", "0.7", "690.7", "0.0001", "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "+100", "--1", "-.1", "-0", "00099", "099"
0