组合两个正则表达式c++0x
Combining two regular expression c++0x
我有一个文本,其中日期可以看起来像这样:2011-02-02
或这样:02/02/2011
,这是我到目前为止所写的,我的问题是,如果有一个很好的方法将这两个正则表达式组合成一个?
std::regex reg1("(\d{4})-(\d{2})-(\d{2})");
std::regex reg2("(\d{2})/(\d{2})/(\d{4})");
smatch match;
if(std::regex_search(item, match, reg1))
{
Date.wYear = atoi(match[1].str().c_str());
Date.wMonth = atoi(match[2].str().c_str());
Date.wDay = atoi(match[3].str().c_str());
}
else if(std::regex_search(item, match, reg2))
{
Date.wYear = atoi(match[3].str().c_str());
Date.wMonth = atoi(match[2].str().c_str());
Date.wDay = atoi(match[1].str().c_str());
}
您可以通过|
将两个正则组合在一起。由于只有一个|
可以匹配,因此我们可以将不同部分的捕获组连接起来,并将它们视为一个整体。
std::regex reg1("(\d{4})-(\d{2})-(\d{2})|(\d{2})/(\d{2})/(\d{4})");
std::smatch match;
if(std::regex_search(item, match, reg1)) {
std::cout << "Year=" << atoi(match.format("$1$6").c_str()) << std::endl;
std::cout << "Month=" << atoi(match.format("$2$5").c_str()) << std::endl;
std::cout << "Day=" << atoi(match.format("$3$4").c_str()) << std::endl;
}
(不幸的是c++ 0x的正则表达式不支持命名捕获组,否则我建议使用命名捕获来循环遍历正则表达式数组)
相关文章:
- 带有多个字符分隔符的正则表达式
- C++:正则表达式匹配代码,打印多个匹配项?
- 查找中间两个数字的正则表达式的匹配项
- C++多个正则表达式条件语法
- 使用 boost::regex (c++) 比较两个正则表达式
- 正则表达式 获取两个换行符之间的文本
- 通过正则表达式拆分字符串会切断结果的第一个字母
- 正则表达式,捕获 4 个被 括起来的数字.或行开始/结束
- 使用正则表达式在字符串中找到多个实例
- 用于匹配多个组的正则表达式
- 在Qt Creator中使用正则表达式在多个文件中查找和替换
- C++正则表达式替换第一个匹配项
- 使用正则表达式查找多个字符串的第一个实例
- 是否可以构造与 3 个或更多非连续 UTF 代码点匹配的 PCRE UTF-8 正则表达式
- 使用正则表达式查找第一个匹配C++索引
- c++将多个正则表达式提取到一个数组中
- 正则表达式,获取两个关键字之间的整个字符串
- 创建单个正则表达式而不是多个正则表达式
- 将两个正则表达式结果连接到一个输出字段中,一次只能使用一个
- 组合两个正则表达式c++0x