regex_search只选择匹配的最大子字符串.还要在regex_search中键入不匹配

regex_search only selecting biggest substring that matches. Also type mismatch in regex_search

本文关键字:regex search 不匹配 字符串 选择      更新时间:2023-10-16

这里的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;
}

首先,你不要用正则表达式解析 HTML。

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

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"));

更新您关于最长比赛的问题 - 您必须使用非贪婪的比赛限定符,例如.*?