Test_User
Test_User

Reputation: 171

Regular expression to allow only one space between words

I've a textbox in an ASP.NET application, for which I need to use a regular expression to validate the user input string. Requirements for regex are -

  1. It should allow only one space between words. That is, total number of spaces between words or characters should only be one.
  2. It should ignore leading and trailing spaces.

Matches:

Non Matches:

Upvotes: 2

Views: 15619

Answers (4)

Adrian
Adrian

Reputation: 46592

Pretty straightforward:

/^ *(\w+ ?)+ *$/

Upvotes: 2

MikeM
MikeM

Reputation: 13641

Assuming there must be either one or two 'words' (i.e. sequences of non-space characters)

"\s*\S+(\s\S+)?\s*"

Change \S to [A-Za-z] if you want to allow only letters.

Upvotes: 3

woemler
woemler

Reputation: 7169

How about:

^\s*(\w+\s)*\w+\s*$

Upvotes: 0

asenovm
asenovm

Reputation: 6517

Maybe this one will do?

\s*\S+?\s?\S*\s*

Edit: Its a server-encoded regex, meaning that you might need to remove one of those escaping slashes.

Upvotes: 0

Related Questions