首页 > 解决方案 > RegEx 用于检查多个匹配项

问题描述

我想匹配字符串中的所有出现。

例子:

pc+pc2/pc2+pc2*rr+pd

我想检查存在多少匹配的pc2值和正则表达式before and after special character

var str = "pc+pc2/pc2+pc2*rr+pd"; 
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));

但我只得到了+pc2/+pc2*/pc2+没有得到这个。

问题是在第一场比赛/被删除。所以在那之后,它开始从pc2+pc2*rr+pd. 这就是为什么/pc2+在比赛中没有价值的原因。

我该如何解决这个问题?

标签: javascriptregexstringregex-groupregex-greedy

解决方案


你需要某种递归正则表达式来实现你想要得到的东西,你可以使用exec来操作lastIndex字符串中的值是p

let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
  op.push(array1[0])
  if(str1[regex1.lastIndex] === 'p'){
    regex1.lastIndex--;
  }
}


console.log(op)


推荐阅读