简体   繁体   中英

Problem with regex lookahead in javascript

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM