Reputation: 135
How can I write regular expression in C# to validate that the input does not contain double spaces? I am using Regular Expression Validation. However I do not know what is the Validation Expression to get the result.
"white snake" : success
"white snake" : fail
Upvotes: 2
Views: 1912
Reputation: 5318
You can use the following .net regular expression to validate the explicit example you have provided.
\w+\s{1}\w+
This regular expression has three parts, from left to right it reads like this - any word character at least one time followed by only one space character followed by any word character at least one time. So \w+ represents any word character at least one time and \s{1} represents any whitespace character only one time.
In the case where you have someone inputting more than two words you might solve it using the above regular expression, but with a set of grouping parens added to it and a bit of code to build the correct number of occurrences of this pattern.
We can take the above regular expression and extend it to look for any number of occurrences of this pattern or in other words for more than just two words. For instance if you have three words instead of two you will have to implement a set of grouping parens to explicitly state how many times this pattern should show up in the string.
For instance if we have the word “white snake valley” and we want to make sure it only has one space between each word you could rewrite the regular express as follows:
(\w+\s{1}\w+){2}
We added grouping parens and stated that the expression only evaluates to true if this pattern is found exactly two times {2}.
Enjoy!
Upvotes: 3
Reputation: 1350
Use the regular expression {2,}
(the first character of that regex is a space).
Upvotes: 1
Reputation: 229643
Search in the input for the substring " "
. If it is found, the input is invalid.
Upvotes: 0