简体   繁体   English

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

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

I'm doing a simple Lookbehind Assertion to get a segment of the URL (example below) but instead of getting the match I get the following error:我正在做一个简单的 Lookbehind Assertion 来获取 URL 的一部分(下面的示例),但不是获取匹配,而是出现以下错误:

Uncaught SyntaxError: Invalid regular expression: /(?<=\#\!\/)([^\/]+)/: Invalid group

Here is the script I'm running:这是我正在运行的脚本:

var url = window.location.toString();

url == http://my.domain.com/index.php/#!/write-stuff/something-else 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 ) );

the result should be write-stuff .结果应该是write-stuff

Can anyone shed some light on why this regex group is causing this error?任何人都可以解释为什么这个正则表达式组会导致这个错误? Looks like a valid RegEx to me.对我来说看起来像一个有效的 RegEx。

I know of alternatives on how to get the segment I need, so this is really just about helping me understand what's going on here rather than getting an alternative solution.我知道如何获得我需要的细分市场的替代方案,所以这实际上只是帮助我了解这里发生的事情,而不是获得替代解决方案。

Thanks for reading.谢谢阅读。

J. J。

I believe JavaScript does not support positive lookbehind.我相信 JavaScript 不支持正向后视。 You will have to do something more like this:你将不得不做更多这样的事情:

<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 doesn't support look-behind syntax, so the (?<=) is what's causing the invalidity error. Javascript 不支持后视语法,因此(?<=)是导致无效错误的原因。 However, you can mimick it with various techniques: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript但是,您可以使用各种技术来模仿它: http : //blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

Also you could use String.prototype.match() instead of RegExp.prototype.exec() in the case of global(/g) or sticky flags(/s) are not set.你也可以使用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