Use a RegularExpressionValidator to limit a word count?
I want to use an ASP.NET RegularExpressionValidator to limit the number of words in a text box. (T开发者_如何转开发he RegularExpressionValidator is my favoured solution because it will do both client and server side checks).
So what would be the correct Regex to put in the RegularExpressionValidator that will count the words and enforce a word-limit? For, lets say, 150 words.
(NB: I see that this question is similar, but the answers given seem to also rely on code such as Split() so I don't think any of them could plug into a RegularExpressionValidator which is why I'm asking again)
Since ^
and $
is implicitly set with RegularExpressionValidators, use the following:
(\S*\s*){0,10}
The 0 here allows empty strings (more specifically 0 words) and 150 is the max number of words to accept. Adjust these as necessary to increase/decrease the number of words accepted.
The above regex is non-greedy, so you'll get a quicker match verses the one given in the question you reference. (\b.*\b){0,10}
is greedy, so as you increased the number of words you'll see a decrease in performance.
Here is a quick reference for regular expressions: http://msdn.microsoft.com/en-us/library/az24scfc.aspx
You can use this site to test the expressions: http://regexpal.com/
Here is my regex example that works with both minimum and maximum word count (and fixes bug with leading spacing):
^\s*(\S+\s+|\S+$){10,150}$
Check this site:
http://lawrence.ecorp.net/inet/samples/regexp-validate.php#count
It's JavaScript RegEx, but it's very similar to asp.net
It's something like this:
(\b[a-z0-9]+\b.*){4,}
精彩评论