C++ 将第一个 boost::regex 匹配放入一个字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15557981/
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 19:29:00  来源:igfitidea点击:

Put first boost::regex match into a string

c++stdstringboost-regex

提问by Tomá? Zato - Reinstate Monica

Somehow, I've failed to find out, how to put only the first occurrence or regular expression to string. I can create a regex object:

不知何故,我没有找到,如何只将第一次出现或正则表达式放入字符串。我可以创建一个正则表达式对象:

static const boost::regex e("<(From )?([A-Za-z0-9_]+)>(.*?)"); 

Now, I need to match ([A-Za-z0-9_]+)to std::string, say playername.

现在,我需要匹配([A-Za-z0-9_]+)std::string,说playername

std::string chat_input("<Darker> Hello");
std::string playername = e.some_match_method(chat_input, 1);   //Get contents of the second (...)

What have I missed?
What should be instead of some_match_methodand what parameters should it take?

我错过了什么?
应该是什么而不是some_match_method它应该采用什么参数?

回答by Loghorn

You can do something like this:

你可以这样做:

static const regex e("<(From )?([A-Za-z0-9_]+)>(.*?)");
string chat_input("<Darker> Hello");
smatch mr;
if (regex_search(begin(chat_input), end(chat_input), mr, e)
    string playername = mr[2].str();   //Get contents of the second (...)

Please note that regex is part of C++11, so you don't need boost for it, unless your regular expression is complex (as C++11 and newer still has difficulties processing complex regular expressions).

请注意,regex 是 C++11 的一部分,因此您不需要提升它,除非您的正则表达式很复杂(因为 C++11 和更新版本仍然难以处理复杂的正则表达式)。

回答by Dave S

I think what you're missing is that boost::regexis the regular expression, but it doesn't do the parsing against a given input. You need to actually use it as a parameter to boost::regex_searchor boost::regex_match, which evaluate a string (or iterator pairs) against the regular expression.

我认为您缺少的是boost::regex正则表达式,但它不会对给定的输入进行解析。您需要实际将其用作boost::regex_searchor的参数boost::regex_match,它会根据正则表达式计算字符串(或迭代器对)。

static const boost::regex e("<(From )?([A-Za-z0-9_]+)>(.*?)"); 
std::string chat_input("<Darker> Hello");
boost::match_results<std::string::const_iterator> results;
if (boost::regex_match(chat_input, results, e))
{
     std::string playername = results[2];  //Get contents of the second (...)
}