Reputation: 17062
How do I write a regular expression for checking if the entered value are all white space or empty or digits. In all other cases it will return false. I tried
\s*|\d+
which is allowing character values too.
Upvotes: 2
Views: 42
Reputation: 627100
Your regex \s*|\d+
just matches 0 or more whitespace or 1 or more digits anywhere inside an input string and it may contain whitespace mixed with digits and other characters.
You can use the following regex:
^(?:\s+|\d+)?$
See demo
The regex matches:
^
- start of string(?:\s+|\d+)?
- 1 or 0 occurrences (due to (?:...)
?
) of...
\s+
- 1 or more whitespace symbols or\d+
- 1 or more digits$
- end of stringIn plain human words,
^....$
- make sure we require a full string match, any partial matches inside a string are not allowed(?:...)?
- all the texts matched with the subpatterns inside this group are optional, thus allowing an empty string match (i.e. return true if the string is empty).Upvotes: 3