Onur
Onur

Reputation: 1155

regex for accepting spaces only between words

I am trying to create a regular expression where the user should enter just a word or words with space between them and its length must have a limit [1 to 32].

For instance, it should accept below line;

wordX[space]wordX[space][space][space]wordX

but it should not accept that:

[space]wordX or wordX[space] or only [space]

wordX must be compatible with this regex:

^(([0-9A-Za-z!"#$%'()*+,./:;=?@^_`{|}~\\\[\]-]))$

Upvotes: 3

Views: 1991

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

Try this:

^(?:\w+\s){0,31}\w+$

\w means: digits, letters, underscore

For strictly accepted chars:

^(?:[\w!"#$%'()*+,./:;=?@^_`{|}~\\\[\]]+\s){0,31}[\w!"#$%'()*+,./:;=?@^_`{|}~\\\[\]]+$

Or:

^(?:\S+\s){0,31}\S+$

\S - any character other than whitespace

Update:

If word length is between 1 and 32 than use this regex:

^(?:\w{1,31}\s)*\w{1,31}$

In the same manner you can modify other regexes.

Upvotes: 1

Related Questions