-1

I want to match all occurrence in string.

Example:

pc+pc2/pc2+pc2*rr+pd

I want to check how many matched of pc2 value and regular expression is before and after special character exists.

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

But I got only +pc2/ and +pc2* and /pc2+ not get in this.

Problem is in first match / is removed. So after that, it is starting to check from pc2+pc2*rr+pd. That's why /pc2+ value does not get in the match.

How do I solve this problem?

Community
  • 1
  • 1
Dhaduk Mitesh
  • 129
  • 2
  • 14

1 Answers1

0

You need some sort of recursive regex to achieve what you're trying to get, you can use exec to manipulate lastIndex in case of value in string is 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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60