Chris So
Chris So

Reputation: 833

Regular expression for no white space at start or end, but allow white space in middle, empty and any 6-20 characters?

I use ^$|^[^\s]+(\s+[^\s]+)*$ to achieve:

  1. no white space at start or end allow white
  2. space in middle
  3. empty string

But how can I put the quantifiers to limit character count in between 6 - 20?

The following should pass

""              <-- (empty string)
"中文"          <-- ( any character)
"A B"          <-- (allow space in middle)
"hi! Hello There"

The following should fail

"A"            <-- (less than 2 number of characters)
" AB"          <-- (space at the start)
"AB "          <-- (space at the end)
" AB "
"test test test test test test"  <--- (more than 20 characters included spaces)

Thanks!

Upvotes: 5

Views: 6499

Answers (2)

anubhava
anubhava

Reputation: 785856

You can use this regex:

^(?:\S.{4,18}\S)?$

Working Demo

Upvotes: 4

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

How about such regex?

^$|^\S.{4,18}\S$

Regular expression visualization

Debuggex Demo

Upvotes: 2

Related Questions