[英]Regex grouping matches with C++ 11 regex library
我正在尝试使用正则表达式进行组匹配。 我想从一个大字符串中提取两个字符串。
输入字符串如下所示:
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
如此, 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;
}
我没有得到任何匹配。 我的正则表达式有什么问题?
您的正则表达式不正确,因为捕获组都没有做您想要的。 第一个是从集合[a-zA-Z0-9]
匹配单个字符,然后是<space>:
,它适用于单个字符的用户名,但没有别的。 第二个捕获组将始终为空,因为您正在寻找零个或多个字符,但也指定匹配不应贪婪,这意味着零字符匹配是有效结果。
修复这两个你的regex
变成
std::regex rgx("WEBMSG #([a-zA-Z0-9]+) :(.*)");
但是简单地实例化一个regex
和一个match_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";
}
"WEBMSG #([a-zA-Z0-9]) :(.*?)"
此正则表达式将仅匹配包含 1 个字符长度的用户名和分号后的任何消息的字符串,但第二组将始终为空,因为尝试找到从 0 到无限制的任何字符的非贪婪匹配较少。
这应该有效:
"WEBMSG #([a-zA-Z0-9]+) :(.*)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.