Javascript/RegExp:Lookbehind 断言导致“无效组”错误
我正在做一个简单的后行断言来获取 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。
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:
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
// 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
.
Can anyone shed some light on why this regex group is causing this error? Looks like a valid RegEx to me.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信 JavaScript 不支持正向回顾。你将不得不做更多类似这样的事情:
I believe JavaScript does not support positive lookbehind. You will have to do something more like this:
Javascript 不支持后视语法,因此
(?<=)
是导致无效错误的原因。但是,您可以使用各种技术来模仿它: http://blog.stevenlevithan.com/archives /mimic-lookbehind-javascriptJavascript doesn't support look-behind syntax, so the
(?<=)
is what's causing the invalidity error. However, you can mimick it with various techniques: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript另外,在全局(/g)或粘性标志(/s)的情况下,您可以使用
String.prototype.match()
而不是RegExp.prototype.exec()
没有设置。Also you could use
String.prototype.match()
instead ofRegExp.prototype.exec()
in the case of global(/g) or sticky flags(/s) are not set.