本文介绍了XRegExp没有回头路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JavaScript中使用正则表达式的后向功能,因此找到了在JavaScript中模拟后向(习作2).另外,我发现作者Steven Levithan是开发 XRegExp 的人.

I need to use lookbehind of regex in JavaScript, so foundSimulating lookbehind in JavaScript (take 2).Also, I found the author Steven Levithan is the one who developed XRegExp.

我git克隆了 XRegExp 3.0.0-pre ,并进行了测试

I git cloned XRegExp 3.0.0-pre, and tested

一些后向逻辑 http://regex101.com/r/xD0xZ5 使用XRegExp

some lookbehind logichttp://regex101.com/r/xD0xZ5using XRegExp

var XRegExp = require('xregexp');
console.log(XRegExp.replace('foobar', '(?<=foo)bar', 'test'));

似乎不起作用;

$ node test
foobar

我想念什么?谢谢.

我的目标是

(?<=foo)[\s\S]+(?=bar)

http://regex101.com/r/sV5gD5

(EDIT2链接错误且已修改)

(EDIT2 the link was wrong and modifed)

答案:

var str = "fooanythingbar";
console.log(str);
console.log(str.replace(/(foo)(?:[\s\S]+(?=bar))/g, '$1test'));

//footestbar

信用归@Trevor资深,谢谢!

Credit goes to @Trevor Senior Thanks!

推荐答案

可以使用非捕获组为此,例如

$ node
> 'foobar'.replace(/(foo)(?:bar)/g, '$1test')
'footest'

String.replace $1的特殊表示法引用了第一个捕获组,在本例中为(foo).通过使用$1test,可以将$1视为第一个匹配组的占位符.展开后,该名称将变为'footest'.

In the second parameter of String.replace, the special notation of $1 references the first capturing group, which is (foo) in this case. By using $1test, one can think of $1 as a placeholder for the first matching group. When expanded, this becomes 'footest'.

有关正则表达式的更多详细信息,请在此处查看其匹配的内容.

For more in depth details on the regular expression, view what it matches here.

这篇关于XRegExp没有回头路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 14:33