javascript 中的正则表达式先行问题

发布于 2024-11-17 15:46:12 字数 662 浏览 5 评论 0原文

我尝试仅在所有空格分隔的单词长度超过 3 个单词字符时进行匹配(3 个单词字符是强制性的,abc* 是正确的,但 ab* 不是)。这是我的测试:

<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>

所有文本都匹配,但我相信没有一个应该匹配。也许我误解了前瞻工作原理的一些基本原理。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘿咻 2024-11-24 15:46:12

测试的简单正则表达式是:

/^(\s?\S{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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文