I'm using regex to validate user input in my Android application.
My business requirement is that user should not be allowed to enter only spaces or only numbers, but should be allowed input of spaces and numbers.
- " " -> not allowed.
- "83278" -> not allowed.
- " 35 46" -> allowed.
Currently I'm using a regex as
^(?![0-9 ]+$).*$
The above reqex is working correctly for requirements #1 and #2 but fails for #3 as it is not allowing user to input spaces and numbers together.
Can someone please help me to improve my reqex to fulfill my requirements.....
Thanking in Advance!
You may use
^(?!(?:[0-9]+| +)$).*$
Or, to support any whitespace
^(?!(?:[0-9]+|\s+)$).*$
See the regex demo and the regex graph:
In Kotlin, use
" 1 2".matches(Regex("""(?!(?:[0-9]+|\s+)$).*""")) // true
Also, you may use ^(?:[0-9]+|\s+)$
pattern and negate the result:
if (" ".matches(Regex("""[0-9]+|\s+"""))) {
println( "INVALID" )
} else {
println( "VALID" )
}
Since .matches()
requires a full string match, no need for ^(?:
and )$
in the above pattern.