Reputation: 975
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.
Upvotes: 78
Views: 276602
Reputation: 13214
Similar 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)$/
Upvotes: 68
Reputation: 1143
This solution matches integers:
/^(0|-*[1-9]+[0-9]*)$/
Upvotes: 3
Reputation: 3594
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
.
Online testing available at http://rubular.com/r/FlnXVL6SOq
Upvotes: 1
Reputation: 39
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
Upvotes: 4
Reputation: 2734
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"
Upvotes: 0
Reputation: 2940
^([+-]?[0-9]\d*|0)$
will accept numbers with leading "+", leading "-" and leadings "0"
Upvotes: 1
Reputation: 47
^(-+)?[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
Upvotes: 0
Reputation: 527133
You could use lookaround instead if all you want to match is whitespace:
(?<=\s|^)\d+(?=\s|$)
Upvotes: 43