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.
有没有人有一个规则表达式可以限制一个回复中单词的数量?例如,我想在jQuery validate中使用它,这样我就可以将文本框/textarea限制为250个单词。箱子将是纯文本。
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.
我用谷歌搜索了一下,但是没有一个是很好的。它们主要集中在做\b\w+\b上,但我很难让它工作。
4 个解决方案
#1
8
Could you try:
你可以尝试:
^(?:\b\w+\b[\s\r\n]*){1,250}$
That would limit to 250 words over multiple lines.
这将限制多行250个字。
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
在嵌套重复操作符时,务必确保只有一种方法匹配相同的匹配
#2
3
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.
用一个regex(比如“\s+”)分割文本,然后计算结果列表的长度,怎么样?这样更容易读。
#3
1
This has worked well for me, for example if you want a 6-word limit:
这对我来说很有效,例如,如果你想要一个6字的限制:
^(?:\w+\W+){0,5}(?:\w+)$
#4
0
Here is the regular expression I use for the word count validation.
下面是我用于单词计数验证的正则表达式。
(\w*\W*){0,250}
#1
8
Could you try:
你可以尝试:
^(?:\b\w+\b[\s\r\n]*){1,250}$
That would limit to 250 words over multiple lines.
这将限制多行250个字。
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
在嵌套重复操作符时,务必确保只有一种方法匹配相同的匹配
#2
3
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.
用一个regex(比如“\s+”)分割文本,然后计算结果列表的长度,怎么样?这样更容易读。
#3
1
This has worked well for me, for example if you want a 6-word limit:
这对我来说很有效,例如,如果你想要一个6字的限制:
^(?:\w+\W+){0,5}(?:\w+)$
#4
0
Here is the regular expression I use for the word count validation.
下面是我用于单词计数验证的正则表达式。
(\w*\W*){0,250}