c++ - 如何在 C++ 中正则表达式方括号“[]”?
问题描述
这是正则表达式:
((([a-z])*Map|map)\\[((MapFields::([a-z]|[A-Z])*)|(([a-z]|[A-Z])*))|("([a-z]|[A-Z]|[0-9]|_)*")*\\]( )*=( )*([a-z]|[A-Z])*;)
这些是我的测试用例:
- 地图[MapFields::abCd] = abCd;
- myMap[MapFields::abCd] = abCd;
- 地图[abCd] = AbCd;
- 地图[AbCd] = abCd;
- 地图[AbCd] = abCd;
- 我的地图[AbCd] = abCd;
- 地图[“AB123”]=abCd;
- 地图["AB_CD"]=abCd;
- 地图["AB_CD"]=abCd;
这在这里工作正常:https ://regexr.com
但是,当我尝试使用 C++11 regex.h 验证我的案例时。我得到无效的匹配。我发现这是因为我需要转义方括号。
这是C++代码,
string data[10] = {
//array of cases
};
try {
regex rgx(regex string);
for ( int i = 0 ; i < 10 ; i++ ) {
if ( regex_match(data[i], rgx) ) {
cout << "string literal matched\n";
}
else {
cout << "string literal unmatched\n";
}
}
}
catch ( exception ex ) {
cout << "Exception: " << ex.what() << endl;
}
我该如何转义方括号,以便我的代码可以正常工作。
谢谢 :)
解决方案
简化后,您可以这样做:
int main()
{
std::string data[] = {
"map[MapFields::abCd] = abCd;",
"myMap[MapFields::abCd] = abCd;",
"map[abCd] = AbCd;",
"map[AbCd] = abCd;",
"map[AbCd] = abCd;",
"myMap[AbCd] = abCd;",
"map[\"AB123\"]=abCd;",
"map[\"AB_CD\"]=abCd;",
"map[\"AB_CD\"]=abCd;"
};
try {
std::regex rgx(R"(((?:[a-z])*Map|map)\[(MapFields::[a-zA-Z]*|[a-zA-Z]*|"[a-zA-Z0-9_]*")\]\s*=\s*([a-zA-Z]*);)");
for (const auto& s : data) {
std::smatch res;
if (std::regex_match(s, res, rgx) ) {
std::cout << s << " [matched]\n";
for (auto e : res) {
std::cout << e << std::endl; // Display matched groups
}
} else {
std::cout << s << " [unmatched]\n";
}
}
}
catch (const std::exception& ex) {
std::cout << "Exception: " << ex.what() << std::endl;
}
}
推荐阅读
- c# - 使用 C# 发布 Apple 新闻 API 的文章 - (401) 未经授权
- javascript - 在嵌套的 json 对象中插入数据
- php - 如何将我的查询限制为每个类别仅获取 5 个产品?
- php - 使用 laravel voyager 管理面板部署 Web 应用程序
- html - 在图像上放置标题
- eclipse - 如何通过存储库更新更改 Eclipse 产品的 jre
- python - 将单个大文件从客户端加载到 dask 工作人员
- ruby-on-rails - 基于版本的 Rails 纸轨关联
- javascript - 该链接也在窗口和弹出窗口中打开
- mongodb - MongoDB 单一/中央 authSource 与多个/分布式 authSource