【问题标题】:Javascript/RegExp: Lookbehind Assertion is causing a "Invalid group" errorJavascript/RegExp:Lookbehind Assertion 导致“无效组”错误
【发布时间】:2011-05-12 05:31:14
【问题描述】:

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

【问题讨论】:

  • 你能举一些输入字符串的例子吗?它的哪一部分必须用正则表达式匹配?
  • 我已将其从代码块中移至主要示例。以上更新。如果您需要更多详细信息,请告诉我,我会很乐意发布。

标签: javascript jquery regex match lookbehind


【解决方案1】:

我相信 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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      在未设置全局(/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"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 1970-01-01
        • 1970-01-01
        • 2020-08-12
        • 2021-12-22
        相关资源
        最近更新 更多