[regex] Regex that matches integers in between whitespace or start/end of string only

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.

This question is related to regex

The answer is


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"


All you want is the below regex:

^\d+$

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"


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


^(-+)?[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


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 just allow positive integers.

^[0-9]*[1-9][0-9]*$

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)$/