在 C++ 中检索正则表达式搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12908534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:44:59  来源:igfitidea点击:

Retrieving a regex search in C++

c++regex

提问by RDismyname

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

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

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

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

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

Now when I do a regex_searchwith 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++.

现在当我regex_search对字符串和上面的表达式做 a时,我可以找到字符串中是否有时间。但我想把那个时间存储在一个结构中,这样我就可以分开小时和分钟。我正在使用 Visual Studio 2010 C++。

回答by Some programmer dude

If you use e.g. std::regex_searchthen it fills in a std::match_resultwhere you can use the operator[]to get the matched strings.

如果您使用 eg ,std::regex_search那么它会填入一个std::match_result您可以使用operator[]来获取匹配字符串的地方。

Edit:Example program:

编辑:示例程序:

#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);
}

Output from the program:

程序的输出:

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

回答by kuperspb

Just use named groups.

只需使用命名组。

(?<hour>(1[0-2]|0?[1-9]))([:](?<minute>[0-5][0-9]))?(am|pm)

Ok, vs2010 doesn't support named groups. You already using unnamed capture groups. Go through them.

好的,vs2010 不支持命名组。您已经在使用未命名的捕获组。通过他们。