Regex to block only numbers or only spaces, but allow numbers and spaces as input

Zeba :

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.

  1. " " -> not allowed.
  2. "83278" -> not allowed.
  3. " 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!

Wiktor Stribiżew :

You may use

^(?!(?:[0-9]+| +)$).*$

Or, to support any whitespace

^(?!(?:[0-9]+|\s+)$).*$

See the regex demo and the regex graph:

enter image description here

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141846&siteId=1