skd
skd

Reputation: 165

Unable to match blank spaces regex

I am trying to match a regex criteria in json schema validation where a string should not accept blank spaces if entire string consists of blank spaces or blank spaces are between any input, but should accept if there are any blank spaces before and after characters, numbers or any special characters

Say

str = "  " 

should not be accepted

or

str = "ab cd" 

should not be accepted. But

str = "abcd  " 

should be accepted or

str = "  abcd" 

should be accepted.

I have used below regex pattern

"pattern":"^[^\\s]*$"

But this is not accepting any blank spaces in the string. All the above scenarios mentioned is showing invalid.

Upvotes: 0

Views: 604

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may use

"pattern":"^\\s*\\S+\\s*$"

See the regex demo

Details

  • ^ - start of string
  • \s* - 0+ whitespaces
  • \S+ - 1+ non-whitespace chars
  • \s* - 0+ whitespaces
  • $ - end of string.

Upvotes: 3

Related Questions