tags:

views:

617

answers:

3

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.

+1  A: 

How about splitting the text with a regex (say "\s+") and then counting the length of the resulting list? That would be somewhat easier to read.

Jay Kominek
+3  A: 

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

VonC
This seemed to work in my tests. I'm not sure if this version has any downsides but I'm going to accept this one for now.
Jonathan
A: 

Hi, Vonc,

The regular expression which you gave: ^(?:\b\w+\b[\s\r\n]*){1,250}$ to limit 250 words over multiple lines works if it doesnt have any special characters... what should i do if i need to search for number of words which also consists special characters... Some thing like this an example: --> Hi! i need help with regular expression, please help me. <--