Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex allow only numbers or empty string

Tags:

regex

Can someone help me create this regex. I need it to check to see if the string is either entirely whitespace(empty) or if it only contains positive whole numbers. If anything else it fails. This is what I have so far.

/^\s*|[0-9][0-9]*/ 
like image 785
IamBanksy Avatar asked Jul 14 '10 17:07

IamBanksy


2 Answers

You're looking for:

/^(\s*|\d+)$/ 

If you want a positive number without leading zeros, use [1-9][0-9]*

If you don't care about whitespaces around the number, you can also try:

/^\s*\d*\s*$/ 

Note that you don't want to allow partial matching, for example 123abc, so you need the start and end anchors: ^...$.
Your regex has a common mistake: ^\s*|\d+$, for example, does not enforce a whole match, as is it the same as (^\s*)|(\d+$), reading, Spaces at the start, or digits at the end.

like image 93
Kobi Avatar answered Sep 20 '22 19:09

Kobi


To match a number or empty string '' i.e the user has not entered any input do this

(^[0-9]+$|^$) 

To match a number, an empty string, or a white space character

(^[0-9]+$|^$|^\s$) 

Test this on regex101

like image 34
Dr Manhattan Avatar answered Sep 21 '22 19:09

Dr Manhattan