在C ++中检索正则表达式搜索 [英] Retrieving a regex search in C++

查看:109
本文介绍了在C ++中检索正则表达式搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我是新的正则表达式,从我从c ++参考网站的理解可以得到匹配的结果。

Hello I am new to regular expressions and from what I understood from the c++ reference website it is possible to get match results.

我的问题是:检索这些结果? smatch cmatch 之间有什么区别?例如,我有一个由日期和时间组成的字符串,这是我写的正则表达式:

My question is: how do I retrieve these results? What is the difference between smatch and cmatch? For example, I have a string consisting of date and time and this is the regular expression I wrote:

"(1[0-2]|0?[1-9])([:][0-5][0-9])?(am|pm)"

现在,当我用字符串和上面的表达式做一个 regex_search 时,我可以找到是否有一个时间在字符串或不。但我想把这个时间存储在一个结构中,所以我可以分开的小时和分钟。我使用Visual studio 2010 c ++。

Now when I do a regex_search with the string and the above expression, I can find whether there is a time in the string or not. But I want to store that time in a structure so I can separate hours and minutes. I am using Visual studio 2010 c++.

推荐答案

std :: regex_search ,然后它填入 std :: match_result 其中可以使用 operator [] 以获取匹配的

If you use e.g. std::regex_search then it fills in a std::match_result where you can use the operator[] to get the matched strings.

编辑示例程序:

#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 << "Match\n";

        //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 match\n";
}

int main()
{
    const std::string time1 = "9:45pm";
    const std::string time2 = "11:53am";

    test_regex_search(time1);
    test_regex_search(time2);
}

程序输出:


Match
match[1] = 9
match[4] = 45
match[5] = pm
Match
match[1] = 11
match[4] = 53
match[5] = am

这篇关于在C ++中检索正则表达式搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆