Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - only allow single spaces within a string

Tags:

c#

regex

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)?

like image 949
HotblackDesiato Avatar asked Feb 16 '23 15:02

HotblackDesiato


1 Answers

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)

like image 84
Damien_The_Unbeliever Avatar answered Feb 23 '23 07:02

Damien_The_Unbeliever