Javascript/RegExp: 向后断言导致“无效组”错误

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

这段文本的意思是:网址为 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.

你可以给出一些输入字符串的例子,说明正则表达式需要匹配哪一部分吗? - Shekhar
我已将它从代码块中移动到主示例中。已更新如上。如果您需要更多细节,请告诉我,我会很乐意发布它。 - Jannis
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>

7

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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接