Regex to find comments with a word inside them

Question:

I have the next regex:

comment_pattern = "(/*[wW]**/)"

With it I am able to search match strings like bellow:

/*
blablabla example 
blabla
*/

Basically I would also like to search in those comments for the variable Compiler_Warning -> in case its inside a multiline comment to get all the expression-> Can some one tell me how to get it.
Basically my regex should return a match for :

/* blabla
Compiler_Warning blablalba
*/

But not for the first example.

Asked By: Adrian Vulpeanu

||

Answers:

Try (regex demo):

import re

text = """
/*
blablabla example 
blabla
*/

Not comment

/* blabla
Compiler_Warning blablalba
*/"""

pat = re.compile(r"/*(?=(?:(?!*/).)*?Compiler_Warning).*?*/", flags=re.S)

for comment in pat.findall(text):
    print(comment)

Prints:

/* blabla
Compiler_Warning blablalba
*/
Answered By: Andrej Kesely

If you don’t want to cross matching /* and */ in between the start and ending in your examples:

(?s)/*(?:(?!*/|/*).)*?bCompiler_Warningb(?:(?!*/|/*).)**/

Explanation

  • (?s) Inline modifier to have the dot also match a newline
  • /* Match /*
  • (?:(?!*/|/*).)*? Match any character if not directly followed by */ or /*
  • bCompiler_Warningb Match literally between word boundaries
  • (?:(?!*/|/*).)* Match any character if not directly followed by */ or /*
  • */ Match */

See a regex demo and a Python demo

Answered By: The fourth bird
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.