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 –
- It should allow only one space between words. That is, total number of spaces between words or characters should only be one.
- It should ignore leading and trailing spaces.
Matches:
- Test
- Test abc
Non Matches:
- Test abc def
- Test abc –> I wanted to include multiple spaces between the 2 words. However the editor ignores these extra spaces while posting a question.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Assuming there must be either one or two ‘words’ (i.e. sequences of non-space characters)
"s*S+(sS+)?s*"
Change S to [A-Za-z] if you want to allow only letters.
Method 2
Pretty straightforward:
/^ *(w+ ?)+ *$/
Fiddle: http://refiddle.com/gls
Method 3
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.
Method 4
How about:
^s*(w+s)*w+s*$
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0