0

I'm trying to match only when all space-separated words are longer than 3 word characters (3 word characters are mandatory, abc* is right but ab* is not). This is my test:

<html>
        <body>
                <script>
                var re = /(?!(\W|^)\w{0,2}(\W|$)).*/i;
                var texts = new Array("ab","ab*","abc de*", "ab* def");
                for (textindex in texts)
                {
                        var text = texts[textindex];
                        var matched = re.test(text);
                        document.write(matched + "<br/>")
                }
                </script>
        </body>
</html>

All texts match, but I believe that none should match. Maybe I'm misunderstanding some fundamental on how lookahead works.

1 Answer 1

3

The simple regex to test that would be:

/^(\s?\S{3,})+$/

As for why your regex isn't working, your negative look-ahead simply means "this does not exist at this exact point", so no matter what your input is you'll get a match at the end of the line at the very least.

Sign up to request clarification or add additional context in comments.

4 Comments

But that one doesn't match "abc*" or "abcd* def*" and both should match.
Ok, I added \S* at the end, and at least that matched all my test patterns. Thanks! So the final answer should be: /^(\s?\w{3,}\S*)+$/
\w was right, I needed 3 forced word characters, and THEN any nonspace (asterisk, in my examples). "ab*" shouldn't match. (maybe this wasn't clear in the original question, I'll clarify this point.
I find your explanation of my lookahead not working interesting, but I don't get it. If the lookaheads always match at the end of the line, I don't see how do you get one that works. Could you please ellaborate ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.