regex_search只选择匹配的最大子字符串。同样在regex_search中键入不匹配

时间:2015-06-29 11:34:54

标签: c++ regex c++11

此处的regex_search仅选择此程序中最长的子字符串,因为输出是整个字符串数据。 这是默认行为吗?

另外,如果我传递字符串而不首先将其声明为字符串

regex_search("<html><body>some data</body></html",m,samepattern)

抛出类型不匹配的错误。

此外,如果我只使用没有额外的第二个参数

regex_search("some string",pattern);

它有效。

整个代码如下所示

#include<string>
#include<regex>
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
   smatch m;
   string data{"<html><body>some data</body></html"};
   bool found = regex_search(data,m,regex("<.*>.*</.*>"));
   //If regex_seacrh("<html><body>some data</body></html",same as above)
   //it throws type mismatch error for this string in regex header
   cout<<(found?m.str():"not found");
   return 0;
}

1 个答案:

答案 0 :(得分:2)

首先,you don't parse HTML with regex

但是,如果你这样做,你确实在调用中有参数不匹配

smatch m;
bool found = regex_search("some data", m, regex("some regex"));

相应的regex_search()重载必须是:

template <class charT, class Allocator, class traits>
bool regex_search(const charT* str,
    match_results<const charT*, Allocator>& m,
    const basic_regex<charT, traits>& e,
    regex_constants::match_flag_type flags =
    regex_constants::match_default);

m的类型为smatch match_results<std::string::const_iterator>

您应该使用cmatch代替smatch

cmatch m;
bool found = regex_search("some data", m, regex("some regex"));
关于最长匹配的问题

更新 - 您必须使用非贪婪的匹配限定符,例如.*?