javascript 中的正则表达式先行问题
我尝试仅在所有空格分隔的单词长度超过 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
测试的简单正则表达式是:
至于为什么你的正则表达式不起作用,你的负向前瞻只是意味着“在这个确切的点上不存在”,所以无论你的输入是什么,你都会得到一个匹配至少在该行的末尾。
The simple regex to test that would be:
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.