Martin Shishkov
Martin Shishkov

Reputation: 2837

Regex to match trimmed string consisting of words separated by only 1 space char

I am looking for a regex to validate input in C#. The regex has to match an arbitrary number of words which are separated with only 1 space character in between. The matched string cannot start or end with whitespace characters (this is where my problem is).

Example: some sample input 123

What I've tried: /^(\S+[ ]{0,1})+$/gm this pattern almost does what is required but it also matches 1 trailing space.

Any ideas? Thanks.

Upvotes: 0

Views: 339

Answers (1)

René Vogt
René Vogt

Reputation: 43906

I tried this one and it seems to work:

Regex regex = new Regex(@"^\S+([ ]{1}\S+)*$");

It checks if your string starts with a word followed by zero or more entities of a single white space followed by a word. So trailing white spaces are not allowed.

Upvotes: 2

Related Questions