我的c ++正则表达式匹配有什么问题

时间:2011-02-20 19:42:13

标签: c++ boost-regex

我正在用c ++写一个robots.txt解析器

 boost::regex exrp( "^User-agent:\s*(.*)");

                 boost:: match_results<string::const_iterator> what;

                  if(boost::regex_search( robots, what, exrp ) )

                  {

                      string s( what[1].first, what[1].second );


                      cout<< s;
                  }

这应该与使用名称*的useragent匹配,但它返回所有数据

2 个答案:

答案 0 :(得分:4)

如果不使用c ++ 0x原始字符串,则需要双反斜杠'\\'。

答案 1 :(得分:2)

如果您希望它仅匹配 User-agent: *而不是(例如)User-agent: webcrawler,则需要

"^User-agent:\\s*\\*"

*字符具有特殊含义,因此必须使用\进行转义。代码中的(.*)匹配任意字符的零次或多次,并捕获匹配项。

编辑:您还需要按橡胶靴指出的那样转义反斜杠。