gpt4 book ai didi

c++ - regex_search 只选择匹配的最大子串。还要在 regex_search 中键入不匹配

转载 作者:行者123 更新时间:2023-11-28 02:24:47 28 4
gpt4 key购买 nike

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

最佳答案

首先,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"));

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

关于c++ - regex_search 只选择匹配的最大子串。还要在 regex_search 中键入不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31114633/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com