你希望找出 c 语言的注释中的内容,它们是包含在 /* 和 */ 之间,不过你并不希望匹配的结果把 /* 和 */ 也包括进来,那么你可以这样用: s = '/* comment 1 */ code /* comment 2 */'
时间: 2023-04-10 11:03:21 浏览: 63
答案:可以使用正则表达式来匹配注释内容,如下所示:
```c
#include <stdio.h>
#include <regex.h>
int main() {
char *s = "/* comment 1 */ code /* comment 2 */";
regex_t regex;
regmatch_t match[1];
const char *pattern = "/\\*([^*]|\\*+[^*/])*\\*+/";
if (regcomp(®ex, pattern, REG_EXTENDED) != 0) {
printf("Failed to compile regex pattern\n");
return 1;
}
while (regexec(®ex, s, 1, match, 0) == 0) {
printf("Matched: %.*s\n", match[0].rm_eo - match[0].rm_so, s + match[0].rm_so);
s += match[0].rm_eo;
}
regfree(®ex);
return 0;
}
```
这段代码使用了 POSIX 正则表达式库,通过编译正则表达式 `/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//` 来匹配注释内容。其中,`[^*]` 表示除了 `*` 以外的任意字符,`[\r\n]` 表示换行符,`\*+` 表示一个或多个 `*`,`[^*/]` 表示除了 `*` 和 `/` 以外的任意字符。这个正则表达式的含义是:匹配以 `/*` 开头、以 `*/` 结尾的注释内容,中间可以包含任意字符,包括换行符和 `*`,但不能包含 `*/`。