Limit the number of lines or words using regex in

2019-09-13 20:52发布

问题:

Does anybody know any regex to restrict a string to specified number of lines and words for data validation of a field in google forms?

I have already tried the following expression

^(?:\b\w+\b[\s\r\n]*){1,250}$

That would limit to 250 words over multiple lines.

but it is not working when there is any special character in the string. Any help would be appreciated.

回答1:

Your [\s\r\n] matches any whitespace chars only. You may use \W to match any non-word char:

^\w+(?:\W+\w+){0,249}$
       ^^

Details:

  • ^ - start of string
  • \w+ - 1+ word chars
  • (?:\W+\w+){0,249} - 0 to 249 (1 to 250 in total) sequences of:
    • \W+ - 1+ non-word chars
    • \w+ - 1+ word chars (that is, words separated with 1+ symbol, whitespace or punctuation)
  • $ - end of string.