Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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.

like image 216
Air In Avatar asked Jan 28 '12 06:01

Air In


2 Answers

All you want is the below regex:

^\d+$ 
like image 93
manojlds Avatar answered Oct 13 '22 04:10

manojlds


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)$/ 
like image 41
ghiscoding Avatar answered Oct 13 '22 04:10

ghiscoding