regex 正则表达式查找包含单词的注解

zbdgwd5y  于 2022-11-18  发布在  其他
关注(0)|答案(2)|浏览(133)

我有下一个正则表达式:

  1. comment_pattern = "(/\*[\w\W]*\*/)"

有了它,我能够搜索匹配字符串如below:

  1. /*
  2. blablabla example
  3. blabla
  4. */

基本上我也想在这些注解中搜索变量Compiler_Warning -〉以防它在多行注解中得到所有表达式-〉有人能告诉我如何得到它吗?基本上我的正则表达式应该返回一个匹配:

  1. /* blabla
  2. Compiler_Warning blablalba
  3. */

但不是第一个例子。

8yparm6h

8yparm6h1#

尝试(regex demo):

  1. import re
  2. text = """\
  3. /*
  4. blablabla example
  5. blabla
  6. */
  7. Not comment
  8. /* blabla
  9. Compiler_Warning blablalba
  10. */"""
  11. pat = re.compile(r"/\*(?=(?:(?!\*/).)*?Compiler_Warning).*?\*/", flags=re.S)
  12. for comment in pat.findall(text):
  13. print(comment)

印刷品:

  1. /* blabla
  2. Compiler_Warning blablalba
  3. */
展开查看全部
0pizxfdo

0pizxfdo2#

如果不想在示例的开头和结尾之间交叉匹配/**/

  1. (?s)/\*(?:(?!\*/|/\*).)*?\bCompiler_Warning\b(?:(?!\*/|/\*).)*\*/

说明

  • (?s)内联修饰符,使点也与换行符匹配
  • /\*匹配/*
  • (?:(?!\*/|/\*).)*?匹配后面没有直接跟*//*的任何字符
  • \bCompiler_Warning\b在单词边界之间逐字匹配
  • (?:(?!\*/|/\*).)*匹配后面没有直接跟*//*的任何字符
  • \*/匹配*/

请参阅regex demoPython demo

相关问题