如何用正则匹配一个JSON字符串
时间: 2023-05-12 19:06:36 浏览: 63
可以使用以下正则表达式来匹配一个JSON字符串:
```
^[\{\[](.|\n)*[\}\]]$
```
其中,^表示字符串的开头,$表示字符串的结尾,[\{\[]表示匹配左括号{或[,(.|\n)*表示匹配任意字符或换行符0次或多次,[\}\]]表示匹配右括号}或]。
相关问题
C++ 使用正则表达式解析json字符串
C++ 标准库提供了一个正则表达式库 `std::regex`,可以用它来匹配和解析 JSON 字符串。下面是一个简单的例子:
```c++
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
// JSON 字符串
string jsonStr = "{\"name\":\"Tom\",\"age\":18,\"gender\":\"male\"}";
// 匹配 JSON 键值对的正则表达式
regex reg("\"(\\w+)\":\"([^\"]+)\"");
// 迭代器来搜索匹配项
sregex_iterator it(jsonStr.begin(), jsonStr.end(), reg);
sregex_iterator end;
// 输出匹配到的键值对
while (it != end) {
cout << it->str(1) << " : " << it->str(2) << endl;
++it;
}
return 0;
}
```
输出结果:
```
name : Tom
age : 18
gender : male
```
这个例子展示了如何用正则表达式来匹配 JSON 字符串中的键值对。在这个例子中,我们使用了一个正则表达式 `\"(\\w+)\":\"([^\"]+)\"`,它表示匹配一个键值对,键是一个由字母和数字组成的单词,值是一个不包含双引号的字符串。然后我们用 `sregex_iterator` 来搜索匹配项,迭代器会在 JSON 字符串中找到所有匹配的键值对,并输出它们的键和值。
C语言正则解析json字符串
在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解析库来得方便和安全。