Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex that allows 5-10 characters but can have spaces in-between not counting

Tags:

regex

Problem

Build a regex statement that allows the following:

  1. minimum 5 characters
  2. maximum 10 characters
  3. can contain whitespace but whitespace does not increment character count
  4. any non-whitespace characters increment character count

Test Cases:

 expected_to_pass = ['testa', ' test a', 12342, 1.234, 'test a']
 expected_to_fail = [' test', 'test ', ' test ', '     ', 1234, 0.1, '           ','12345678901']

Example regex statements and their purpose

Allow 5-10 non-whitespace characters:

[\S]{5,10}$

Allow 5-10 characters regardless of whitespace:

[\s\S]{5,10}$

I've been farting around with this for a few hours and cannot think of the best way to handle this.

like image 745
gwnp Avatar asked Dec 23 '22 21:12

gwnp


1 Answers

How's this?

\s*(?:[\w\.]\s*){5,10}+$

Or:

\s*(?:[\w\.]\s*){5,10}$

Also, if ANY non-whitespace character goes:

\s*(?:\S\s*){5,10}$

You can test it here

like image 176
maksymiuk Avatar answered May 23 '23 13:05

maksymiuk