HotblackDesiato
HotblackDesiato

Reputation: 348

Regex - only allow single spaces within a string

I need to restrict a string to only allow letters, numbers, hyphens, ampersands, apostrophes and single spaces.

From a bit of searching I've got this so far:

^[A-Za-z0-9-'&\s]{1,}$

But this allows for double spaces. How do I write the regular expression so that it only allows single spaces (there might not be any at all)?

Upvotes: 4

Views: 1127

Answers (3)

MayankGaur
MayankGaur

Reputation: 993

I have tried with different scenario it works fine with me ^\b(?!.*?\s{2})[A-Za-z0-9 ]{1,50}\b$

[RegularExpression(@"^\b(?!.*?\s{2})[A-Za-z0-9 ]{1,50}\b$", ErrorMessage ="String is not valid"]
public string FirstName{ get; set; }

Upvotes: 0

Sergey K
Sergey K

Reputation: 4114

Try this
^([A-Za-z0-9-'&]+\s?)+$

Upvotes: 1

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239814

Match any of the other allowed values, followed by an optional single space:

^\s?([A-Za-z0-9-'&]\s?){1,}$

(I also added an optional one at the start, if that's allowed)

Upvotes: 7

Related Questions