python正则表达式匹配c语言注释
时间: 2024-01-12 14:46:24 浏览: 84
可以使用以下正则表达式匹配C语言注释:
```
\/\*[\s\S]*?\*\/|\/\/.*
```
该正则表达式使用了两个模式,分别匹配多行注释和单行注释。具体解释如下:
- `\/\*[\s\S]*?\*\/` 匹配多行注释,其中:
- `\/\*` 匹配 `/*` 字符串
- `[\s\S]*?` 匹配任意字符,包括换行符,非贪婪模式
- `\*\/` 匹配 `*/` 字符串
- `\/\/.*` 匹配单行注释,其中:
- `\/\/` 匹配 `//` 字符串
- `.*` 匹配任意字符,不包括换行符
示例代码:
```python
import re
source_code = """
#include <stdio.h>
/*
* This is a multiline comment
* that can span multiple lines
*/
int main() {
int x = 10; // This is a single line comment
printf("Hello, world!");
return 0;
}
"""
pattern = r"\/\*[\s\S]*?\*\/|\/\/.*"
comments = re.findall(pattern, source_code)
for comment in comments:
print(comment)
```
输出结果:
```
/*
* This is a multiline comment
* that can span multiple lines
*/
// This is a single line comment
```
阅读全文