Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the number of words in a response with a regular expression

Tags:

regex

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.

like image 668
Jonathan Avatar asked Feb 17 '09 16:02

Jonathan


People also ask

How do you restrict the length of a regular expression?

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.

How do you check for multiple words in a regular expression?

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.

How range of characters are used in regular expression?

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'.

What is () in regular expression?

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.


1 Answers

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

like image 178
VonC Avatar answered Oct 13 '22 08:10

VonC