Michael Galos
Michael Galos

Reputation: 1085

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 will only match strings which do NOT have words of >=10 characters.

Upvotes: 2

Views: 1378

Answers (2)

polygenelubricants
polygenelubricants

Reputation: 383726

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

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361585

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.

Upvotes: 0

Related Questions