Jan Tacci
Jan Tacci

Reputation: 3201

Regular Expression Match Doesn't Start With, Contain, Or End With Space And Not Empty String

I am writing a C# program that needs to validate an input string to make sure that it doesn't start with a space, doesn't contain a space, and doesn't end with a space.

I am currently using the following regular expression:

^[\S]*$

This works great on all strings except if the string is empty:

"HELLO" (Match)
"H" (Match)
"HE LLO" (No Match)
" HELLO" (No Match)
"HELLO " (No Match)
"" (Match) 

As you can see the empty string "" returns a match which is not what I want.

How do I modify my regular expression to also make sure the string is not empty?

Thank you.

Upvotes: 2

Views: 556

Answers (2)

Jongware
Jongware

Reputation: 22447

It's a bit easier just to test on the presence of

 \s

anywhere ...

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

Just replace the zero-or-more quantifier (*) with a one-or-more quantifier (+). Also, there's no need to wrap the \S in a character class. Try this:

^\S+$

Further Reading:

Upvotes: 2

Related Questions