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.
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
*/
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
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.
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
*/
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