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]*/
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]*/
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 123
abc
, 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.
Kobi has a good answer but technically you don't have to capture it (unless you're going to do something the output)
/^[\s\d]+$/
Or if you don't care if the string is completely empty (i.e. "")
/^[\s\d]*$/
To clarify I understood the original question to mean whitespace in the string should be ignored.