3

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

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

现在,我需要匹配([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 (...)

我错过了什么?
应该用什么代替,应该采用some_match_method什么参数?

4

2 回答 2

6

你可以这样做:

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 (...)

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

于 2013-03-21T21:22:49.607 回答
4

我认为您缺少的是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 (...)
}
于 2013-03-21T21:11:11.587 回答