开发者

Problem with regex lookahead in javascript

开发者 https://www.devze.com 2023-03-16 12:01 出处:网络
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:

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 misunderstandi开发者_运维问答ng 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.

0

精彩评论

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