Javascript/RegExp:Lookbehind Assertion导致“无效组”错误
问题描述:
我正在做一个简单的Lookbehind Assertion来获取网段的一部分(下面的例子),但不是获得匹配我得到以下错误:Javascript/RegExp:Lookbehind Assertion导致“无效组”错误
Uncaught SyntaxError: Invalid regular expression: /(?<=\#\!\/)([^\/]+)/: Invalid group
这里是我运行脚本:
var url = window.location.toString();
url ==
http://my.domain.com/index.php/#!/write-stuff/something-else
// lookbehind to only match the segment after the hash-bang.
var regex = /(?<=\#\!\/)([^\/]+)/i;
console.log('test this url: ', url, 'we found this match: ', url.match(regex));
结果应该是write-stuff
。
任何人都可以阐明为什么这个正则表达式组导致这个错误吗?看起来像一个有效的RegEx给我。
我知道如何获得我需要的细分的替代方案,所以这实际上只是帮助我理解这里发生的事情,而不是获得替代解决方案。
感谢您的阅读。
J.
答
我相信JavaScript不支持正面回顾后。你将不得不做更多的事情是这样的:
<script>
var regex = /\#\!\/([^\/]+)/;
var url = "http://my.domain.com/index.php/#!/write-stuff/something-else";
var match = regex.exec(url);
alert(match[1]);
</script>
答
JavaScript不支持向后看的语法,所以(?<=)
是什么导致了无效的错误。但是,你可以用各种技术来模拟它:http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
你可以给一些示例输入字符串,它的哪些部分必须由正则表达式匹配? – Shekhar 2011-05-12 05:36:37
我已经将它从代码块中移动到主要示例。上面更新。请让我知道你是否想要更多的细节,我会很乐意发布它。 – Jannis 2011-05-12 05:45:17