Does anybody have a regular expression that would work to limit the number of words in a response? For instance, I'd like to use it with jQuery validate so I can restrict a textbox/textarea to have say 250 words. The boxes will be plain-text.
I've done some Googling but none of the ones I've found were very good. They mostly centered around doing \b\w+\b but I had trouble getting it work.
By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.
However, to recognize multiple words in any order using regex, I'd suggest the use of quantifier in regex: (\b(james|jack)\b. *){2,} . Unlike lookaround or mode modifier, this works in most regex flavours.
To show a range of characters, use square backets and separate the starting character from the ending character with a hyphen. For example, [0-9] matches any digit. Several ranges can be put inside square brackets. For example, [A-CX-Z] matches 'A' or 'B' or 'C' or 'X' or 'Y' or 'Z'.
The above regex matches two words (without white spaces) separated by one or more whitespaces. Parentheses () have two meanings in regex: to group sub-expressions, e.g., (abc)* to provide a so-called back-reference for capturing and extracting matches.
Could you try:
^(?:\b\w+\b[\s\r\n]*){1,250}$
That would limit to 250 words over multiple lines.
I am afraid that the Alan's initial proposition:
/^\w+(?:\s+\w+){0,249}$/
might be a case of catastrophic backtracking
When nesting repetition operators, make absolutely sure that there is only one way to match the same match
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With