9

我正在做一个简单的 Lookbehind Assertion 来获取 URL 的一部分(下面的示例),但我没有得到匹配,而是得到以下错误:

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

谁能解释为什么这个正则表达式组会导致这个错误?对我来说看起来像是一个有效的正则表达式。

我知道如何获得我需要的部分的替代方案,所以这实际上只是帮助我了解这里发生了什么,而不是获得替代解决方案。

谢谢阅读。

J。

4

3 回答 3

11

我相信 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>
于 2011-05-12T05:50:23.797 回答
7

Javascript 不支持后视语法,所以这(?<=)就是导致无效错误的原因。但是,您可以使用各种技术来模仿它:http: //blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

于 2011-05-12T05:51:33.310 回答
0

您也可以在未设置全局(/g)或粘性标志(/s)的情况下使用String.prototype.match()代替。RegExp.prototype.exec()

var regex = /\#\!\/([^\/]+)/;
var url = "http://my.domain.com/index.php/#!/write-stuff/something-else";
var match = url.match(regex); // ["#!/write-stuff", "write-stuff", index: 31, etc.,]
console.log(match[1]); // "write-stuff"
于 2020-07-15T07:12:12.530 回答