Shashank Shekhar
Shashank Shekhar

Reputation: 43

regex for allowing SINGLE white space in between words

I m using the following regex for the same: ^\S.*\S$

but this regex is not working in case of multiple spaces in between words. and one more thing, it doesnt allow you to enter a single character

I want to validate no leading and trailing space and single white space in between words, words can include anything alphanumeric as well as special character.

if i m trying to enter 'a' in the text box, its not accepting

Upvotes: 3

Views: 19218

Answers (5)

Kshitij
Kshitij

Reputation: 380

Below one allows one space between words with some special chars. It also prevent space at starting and end of string.

^([a-zA-Z0-9@.,]+\s)*[a-zA-Z0-9@.,]+$

Upvotes: 1

aliawadh980
aliawadh980

Reputation: 468

In case only charactors are needed, use this:

^[a-z|A-Z]+(?: [a-z|A-Z]+)*$

Upvotes: 5

Bohemian
Bohemian

Reputation: 424983

Just assert that two spaces don't appear;

^(?!.*\s\s)\S(.*\S)?$

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Seems like you want something like this,

^\S+(?: \S+)*$

\S matches any non-space character.

DEMO

Upvotes: 6

Sandy Rawat
Sandy Rawat

Reputation: 695

[A-Za-z]+(\s[A-Za-z]+)? you can use this to put single space between words

Upvotes: 0

Related Questions