正则表达式检测可选注释块,后跟条件块

问题描述 投票:0回答:1

我正在尝试编写一个脚本来检测并删除带有可选注释块的文件中的 #ifdef BUILD_FLAG ... #endif 块(如果它出现在它之前)。所以类似的东西将被删除

//this is s comment block
/**
*and a nested comment block
*/
//this is another comment block
#ifdef BUILD_FLAG
...
#endif

我正在尝试用这段代码来做到这一点

block_comment_pattern = r'/\*[\s\S]*?\*/|\/\/.*?$|\/\/.*?(\n|$)'
conditional_block_pattern = (rf'#ifn?def\s+{BUILD_FLAG}\b#endif')
pattern = rf'({block_comment_pattern})?{conditional_block_pattern}'
MATCHER = regex.compile(pattern, re.M)

但是,它只能检测到部分注释块和条件块

//this is another comment block
#ifdef BUILD_FLAG
...
#endif

当我单独测试注释块模式时,它能够捕获整个注释块,但与条件模式结合时则无法捕获。捕获上述示例的更好方法/模式是什么?谢谢你

python regex parsing python-re
1个回答
0
投票

尝试一下是否有效:

BUILD_FLAG = "your_build_flag"
block_comment_pattern = r'/\*[\s\S]*?\*/|\/\/.*?$|\/\/.*?(\n|$)'
conditional_block_pattern = rf'(#ifdef {BUILD_FLAG}\n[\s\S]*?#endif)'
pattern = rf'({block_comment_pattern})?{conditional_block_pattern}'
MATCHER = regex.compile(pattern, flags=regex.MULTILINE | regex.DOTALL)
© www.soinside.com 2019 - 2024. All rights reserved.