Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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!

like image 670
Chris So Avatar asked May 09 '14 08:05

Chris So


People also ask

How do you restrict whitespace in regex?

Trimming Whitespace You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is a non whitespace character in regex?

Whitespace character: \s. Non-whitespace character: \S.

What does \d do in regex?

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets. If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9].


2 Answers

You can use this regex:

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

Working Demo

like image 176
anubhava Avatar answered Sep 19 '22 13:09

anubhava


How about such regex?

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

Regular expression visualization

Debuggex Demo

like image 35
Ulugbek Umirov Avatar answered Sep 22 '22 13:09

Ulugbek Umirov