正则表达式分组与C ++ 11正则表达式库匹配

时间:2015-03-28 18:55:58

标签: c++ regex linux c++11

我正在尝试使用正则表达式进行组匹配。我想从一个大字符串中提取两个字符串。

输入字符串如下所示:

tХB:Username!Username@Username.tcc.domain.com Connected
tХB:Username!Username@Username.tcc.domain.com WEBMSG #Username :this is a message
tХB:Username!Username@Username.tcc.domain.com Status: visible

Username可以是任何东西。同样适用于结束部分this is a message

我想要做的是提取英镑符号#之后的 用户名 。不是来自字符串中的任何其他位置,因为它可以变化。我还想从分号:后面的字符串中获取 消息

我尝试使用以下正则表达式。但它永远不会输出任何结果。

regex rgx("WEBMSG #([a-zA-Z0-9]) :(.*?)");
smatch matches;

for(size_t i=0; i<matches.size(); ++i) {
    cout << "MATCH: " << matches[i] << endl;
}

我没有得到任何比赛。我的正则表达式有什么问题?

2 个答案:

答案 0 :(得分:15)

您的正则表达式不正确,因为两个捕获组都没有执行您想要的操作。第一个是匹配集合[a-zA-Z0-9]后跟<space>:的单个字符,它适用于单个字符的用户名,但没有其他任何内容。第二个捕获组将始终为空,因为您正在寻找零个或多个字符,但是指定匹配也不应该是贪婪的,这意味着零字符匹配是有效的结果。

修复这两个regex变为

std::regex rgx("WEBMSG #([a-zA-Z0-9]+) :(.*)");

但是,只是实例化regexmatch_results对象不会产生匹配,您需要应用regex算法。由于您只想匹配输入字符串的一部分,因此在这种情况下使用的适当算法是regex_search

std::regex_search(s, matches, rgx);

全部放在一起

    std::string s{R"(
tХB:Username!Username@Username.tcc.domain.com Connected
tХB:Username!Username@Username.tcc.domain.com WEBMSG #Username :this is a message
tХB:Username!Username@Username.tcc.domain.com Status: visible
)"};

    std::regex rgx("WEBMSG #([a-zA-Z0-9]+) :(.*)");
    std::smatch matches;

    if(std::regex_search(s, matches, rgx)) {
        std::cout << "Match found\n";

        for (size_t i = 0; i < matches.size(); ++i) {
            std::cout << i << ": '" << matches[i].str() << "'\n";
        }
    } else {
        std::cout << "Match not found\n";
    }

Live demo

答案 1 :(得分:2)

"WEBMSG #([a-zA-Z0-9]) :(.*?)":此正则表达式只匹配字符串,其中包含1个字符长度的用户名和分号后的任何消息,但第二个组将始终为空,因为尝试查找任何字符的较少非贪婪匹配从0到无限。

"WEBMSG #([a-zA-Z0-9]+) :(.*)"应该有用。