使用后向断言完成的Patten匹配。如何使用javascript中的lookbehind进行操作?

时间:2019-05-02 13:17:12

标签: javascript regex

我正在匹配下面描述的三种模式,它们都是独立的。按照超链接在regex操场上观看演示。


模式Get-WmiObject -Query "select DisplayName, State from Win32_Service where State ='Stopped'" | select Displayname, State matches everything beginning from second .


模式/(?<=^[^.]*\.[^.]*)\..*/g,对于仅/(?<=\.\d{2}).*/g的输入字符,matches everything beginning from 3rd digit after first .


模式/[0-9.]/g,对于仅/(?<=\.\d{4}).*/g的输入字符,matches everything beginning from 5th digit after first .


如果不使用JS中的lookbehind,我将无法做到这一点。

1 个答案:

答案 0 :(得分:1)

我要做的是使用小组并抓住最后一个小组。

let r1 = /(\.)[^.]*(\.)(.*)/g;

let m1 = r1.exec('..post dots match');
console.log(m1[m1.length-1]);

let r2 = /(\.\d{2})(.*)/g;

let m2 = r2.exec('.001234');
console.log(m2[m2.length-1]);

let r3 = /(\.\d{4})(.*)/g;
let m3 = r3.exec('.123400000');
console.log(m3[m3.length-1]);