Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to find a string, excluding comments

Tags:

regex

I need a regex to search for the string SQLHELPER that ignores commented code (single line comment or multi line comments). I am searching in visual studio.

like image 298
Sagar Avatar asked Sep 17 '25 06:09

Sagar


1 Answers

You may use

(?<!^[\p{Zs}\t]*//.*)(?<!/\*(?:(?!\*/)[\s\S\r])*?)\bSQLHELPER\b

See the regex demo.

Details

  • (?<!^[\p{Zs}\t]*//.*) - a negative lookbehind that fails the match if, immediately to the left of the current location, the following pattern does not match:
    • ^ - start of line
    • [\p{Zs}\t]* - any 0+ horizontal whitespaces
    • // - a // substring
    • .* - any 0+ chars other than line break chars
  • (?<!/\*(?:(?!\*/)[\s\S\r])*?) - - a negative lookbehind that fails the match if, immediately to the left of the current location, the following pattern does not match:
    • /\* - a /* substring
    • (?:(?!\*/)[\s\S\r])*? - (tempered greedy token) any char (matched with [\s\S\r]), 0 or more repetitions but as few as possible (due to *?) that does not start a */ substring (due to the (?!\*/) negative lookahead)
  • \bSQLHELPER\b - a whole word SQLHelper (\b are word boundaries).

enter image description here

like image 51
Wiktor Stribiżew Avatar answered Sep 22 '25 03:09

Wiktor Stribiżew