C语言正则解析json字符串
时间: 2023-09-21 08:03:34 浏览: 216
在C语言中,可以使用正则表达式来解析JSON字符串。以下是一个简单的示例代码,它使用正则表达式来解析JSON字符串并提取其中的键值对:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#define MAX_MATCHES 10
// 正则表达式匹配错误处理函数
void handle_regex_error(int error_code, regex_t *regex) {
char error_message[100];
regerror(error_code, regex, error_message, sizeof(error_message));
printf("Regex error: %s\n", error_message);
exit(EXIT_FAILURE);
}
int main() {
char *json_str = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
char *pattern = "\"(\\w+)\":\"?([^\"]+)\"?";
regex_t regex;
int ret = regcomp(®ex, pattern, REG_EXTENDED);
if (ret != 0) {
handle_regex_error(ret, ®ex);
}
regmatch_t matches[MAX_MATCHES];
int num_matches = 0;
int start_pos = 0;
while (1) {
ret = regexec(®ex, json_str + start_pos, MAX_MATCHES, matches, 0);
if (ret == REG_NOMATCH) {
break;
} else if (ret != 0) {
handle_regex_error(ret, ®ex);
}
num_matches = matches[0].rm_eo - matches[0].rm_so;
char match[num_matches + 1];
memset(match, 0, sizeof(match));
strncpy(match, json_str + start_pos + matches[0].rm_so, num_matches);
printf("Key: %.*s\n", matches[1].rm_eo - matches[1].rm_so, json_str + start_pos + matches[1].rm_so);
printf("Value: %.*s\n", matches[2].rm_eo - matches[2].rm_so, json_str + start_pos + matches[2].rm_so);
start_pos += matches[0].rm_eo;
}
regfree(®ex);
return 0;
}
```
在这个示例中,我们使用了一个正则表达式来匹配JSON字符串中的键值对。正则表达式的模式为:`"(\w+)":"?([^"]+)"?`,其中:
- `\"` 表示双引号,`\w` 表示任意字母、数字或下划线;
- `(\w+)` 表示匹配一个或多个字母、数字或下划线,并将其作为第一个子匹配;
- `:` 表示冒号;
- `"?` 表示可选的双引号;
- `([^"]+)` 表示匹配一个或多个非双引号字符,并将其作为第二个子匹配;
- `"?"` 表示可选的双引号。
在代码中,我们使用了 `regcomp` 函数来编译正则表达式模式,然后使用 `regexec` 函数来匹配字符串。每次匹配成功后,我们使用 `regmatch_t` 结构体来存储匹配结果,并使用 `strncpy` 函数将匹配的结果复制到一个新的字符串中。最后,我们在循环中更新起始位置,直到整个字符串被处理完毕。
需要注意的是,这只是一个简单的示例代码,仅适用于特定的JSON字符串格式。对于更复杂的JSON字符串,可能需要更复杂的正则表达式模式来解析。此外,使用正则表达式解析JSON字符串可能不如使用专门的JSON解析库来得方便和安全。
阅读全文
相关推荐














