C++ 正则表达式判断是否合格json
时间: 2023-06-20 20:04:57 浏览: 344
可以使用C++中的正则表达式库`<regex>`来判断是否为合法的JSON字符串。以下是一个简单的实现:
```cpp
#include <iostream>
#include <regex>
bool is_valid_json(const std::string& str) {
const std::regex pattern(R"(\s*\{\s*("[^"]*"\s*:\s*(\d+|true|false|null|"\w*")\s*,\s*)*("[^"]*"\s*:\s*(\d+|true|false|null|"\w*")\s*\}\s*)");
return std::regex_match(str, pattern);
}
int main() {
std::string str = R"({"name": "John", "age": 30, "city": "New York"})";
std::cout << is_valid_json(str) << std::endl; // output: 1 (true)
str = R"({"name": "John", "age": 30, "city": "New York",})";
std::cout << is_valid_json(str) << std::endl; // output: 0 (false)
str = R"({"name": "John", "age": 30, "city": "New York", "is_student": true})";
std::cout << is_valid_json(str) << std::endl; // output: 1 (true)
str = R"({"name": "John", "age": 30, "city": "New York", "is_student": True})";
std::cout << is_valid_json(str) << std::endl; // output: 0 (false)
str = R"({"name": "John", "age": 30, "city": "New York", "is_student": null})";
std::cout << is_valid_json(str) << std::endl; // output: 1 (true)
str = R"({"name": "John", "age": 30, "city": "New York", "is_student": "true"})";
std::cout << is_valid_json(str) << std::endl; // output: 1 (true)
return 0;
}
```
这个实现只是一个简单的演示,实际上JSON字符串的规则比这要复杂得多。如果需要处理更复杂的JSON字符串,建议使用专门的JSON库来解析。