检索 C++ 中的正则表达式搜索
Retrieving a regex search in C++
您好,我是正则表达式的新手,根据我从 c++ 参考网站上的理解,可以获得匹配结果。
我的问题是:如何检索这些结果?smatch
和cmatch
有什么区别?例如,我有一个由日期和时间组成的字符串,这是我编写的正则表达式:
"(1[0-2]|0?[1-9])([:][0-5][0-9])?(am|pm)"
现在,当我对字符串和上面的表达式进行regex_search
时,我可以找到字符串中是否有时间。但我想将时间存储在一个结构中,这样我就可以将小时和分钟分开。我正在使用Visual Studio 2010 c++。
如果您使用 例如 std::regex_search
,它会填充一个std::match_result
,您可以在其中使用 operator[]
获取匹配的字符串。
编辑:示例程序:
#include <iostream>
#include <string>
#include <regex>
void test_regex_search(const std::string& input)
{
std::regex rgx("((1[0-2])|(0?[1-9])):([0-5][0-9])((am)|(pm))");
std::smatch match;
if (std::regex_search(input.begin(), input.end(), match, rgx))
{
std::cout << "Matchn";
//for (auto m : match)
// std::cout << " submatch " << m << 'n';
std::cout << "match[1] = " << match[1] << 'n';
std::cout << "match[4] = " << match[4] << 'n';
std::cout << "match[5] = " << match[5] << 'n';
}
else
std::cout << "No matchn";
}
int main()
{
const std::string time1 = "9:45pm";
const std::string time2 = "11:53am";
test_regex_search(time1);
test_regex_search(time2);
}
程序输出:
火柴匹配[1] = 9匹配[4] = 45匹配[5] = 下午火柴匹配[1] = 11匹配[4] = 53匹配[5] = 上午
只需使用命名组。
(?<hour>(1[0-2]|0?[1-9]))([:](?<minute>[0-5][0-9]))?(am|pm)
好的,vs2010 不支持命名组。已在使用未命名的捕获组。通过他们。
相关文章:
- C++向后正则表达式搜索
- 可选搜索和正则表达式
- C++ 中用于搜索字符串模式的正则表达式
- 如何加快正则表达式搜索C++中大量潜在的大文件?
- 正则表达式C++如何搜索有效的 Linux 设备节点
- 对 std::string 执行正则表达式搜索和替换
- Eclipse IDE,正则表达式搜索和替换
- 尝试使用正则表达式搜索:C++
- 检索 C++ 中的正则表达式搜索
- 如何在c++中搜索正则表达式
- 在C++中使用正则表达式搜索.txt文件
- 找不到c++正则表达式搜索模式
- 相同的正则表达式搜索结果在C++和Java中有所不同
- 正则表达式搜索和替换C++中的组?
- C++ 使用正则表达式搜索"正则表达式运算符"
- 我如何在另一个进程的内存中通过正则表达式搜索字符串
- 用C++正则表达式搜索字符串中的文件路径
- 搜索/替换boost正则表达式
- 使用正则表达式搜索向量
- c++正则表达式搜索多行注释(在/* */之间)