javascriptregexmatchregex-lookaroundsnegative-lookbehind

regex to use negative look far behind along with positive look behind?


I need it to select only value which has :this in line but not include which are under comment section (/* */)

I have tried this one which works and give 3 results but it is incorrect as it select the last one which is in comment

const str = `
    :this { 
      display: grid; 
    }

    p { color: red}

    :this { this is also okay to capture  }
    /* but do not capture this :this { } , so how to look far behind here */
`;

const pattren = '(?<=:)\\bthis\\b\\s*(?={)';
const rx = new RegExp(pattren, 'gmd');
const matches = str.matchAll(rx);
console.log([...matches]);

Trial 1:

look far behind that is there * in the same line but it does not work and gives 0 result

const pattern = '(?<!/*)(?<=:)\\bthis\\b\\s*(?={)'; 

Solution

  • You can use (?<!/\*.*) to look for /* followed by zero or more characters.

    const str = `
           :this { 
              display: grid; 
            }
    
            p { color: red}
    
             :this { this is also okay to capture  }
            /* but do not capture this :this { } , so how to look far behind here */
        `;
    
    const re = /(?<!\/\*.*)(?<=:)\bthis\b\s*(?={)/gmd;
    const matches = str.matchAll(re);
    console.log([...matches]);