开发者

Regex to match a string that does not contain any words longer than 10 characters?

^(.)+\S{10}(.)+$ 

I have that regex which will match any string that contains a word of 10 characters. However I need the INVERSE of that.

A regex that wi开发者_StackOverflow社区ll only match strings which do NOT have words of >=10 characters.


Use negative assertion.

(?!.*\S{10})

\S{10} matches a sequence of 10 \S (which must be a subsequence of anything longer). (?!pattern) is a negative lookahead, an assertion that is true if the pattern doesn't match. .* allows the lookahead to look as far as necessary.

The whole pattern therefore is

^(?!.*\S{10}).*$

This matches all string that do NOT contain \S{10}.

See also

  • regular-expressions.info/Lookarounds


Untested:

^\s*\S{0,9}(\s+\S{1,9})*\s*$

Matches one or more words. The first word is optional, so the empty string or a string of all whitespace will match. The words must be separated by whitespace \s+ so no more than 9 \S characters can ever be adjacent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜