繁体   English   中英

Javascript/RegExp:Lookbehind Assertion 导致“无效组”错误

[英]Javascript/RegExp: Lookbehind Assertion is causing a "Invalid group" error

我正在做一个简单的 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

任何人都可以解释为什么这个正则表达式组会导致这个错误? 对我来说看起来像一个有效的 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

你也可以使用String.prototype.match()而不是RegExp.prototype.exec()在 global(/g) 或sticky flags(/s) 没有设置的情况下。

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM