我有以下正则表达式

(?<=\.)\S+$


用于提取字符串的扩展名(无论最后一个点之后是什么)。 regex101.com似乎接受我的正则表达式:字符串扩展名正确匹配。一旦将其移入JavaScript脚本并尝试针对字符串进行测试,就会收到此错误:

Invalid regular expression: /(?<=\.)\S+$/: Invalid group


我也用regex101自动生成的代码得到相同的错误:

var re = /(?<=\.)\S+$/;
var str = 'test.txt';
var m;

if ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}


参见小提琴HERE

有什么提示吗?

最佳答案

您不能在JavaScript正则表达式中使用回溯。有一些JavaScript look-behind workarounds,但是它们都有自己的障碍。为了安全起见,请使用捕获组。在这里,您需要的内容将在第二组中:

  (\.)([^.]+)$


或者,只有一个捕获组(以提高性能):

  \.([^.]+)$


码:



var re = /\.([^.]+)$/;
var str = 'test.txt';
var m;

if ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    alert(m[1]);
}

关于javascript - 正则表达式后移:无效的正则表达式:/(?<=\.)\S+$/:无效的组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29370007/

10-11 19:32
查看更多