regex_search只选择匹配的最大子字符串.还要在regex_search中键入不匹配
regex_search only selecting biggest substring that matches. Also type mismatch in regex_search
这里的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"));
更新您关于最长比赛的问题 - 您必须使用非贪婪的比赛限定符,例如.*?
相关文章:
- 此模式的C++RegEx
- QTableview Search
- LeetCode 1011.Binary Search,C++和Python的想法相同,但输出不同
- C++ std::regex 使用前瞻失败
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 二叉搜索树 - 实现"search"函数
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 使用Regex解析cpp中的字符串并创建映射
- C++:如何用split查找单词?Regex
- 在VC2015U3上,std::regex比boost::regex慢得多
- 是否有更有效的方法来生成日期的REGEX字符串
- 在C++中使用带有regex的捕获组
- 将std::regex设置为静态的好主意吗
- 为什么Regex(c++)需要指数时间
- std::regex and dual ABI
- C++11 std::regex后备选项
- 以不同的方式替换每一项,regex c++
- 使用 boost::regex (c++) 比较两个正则表达式
- 如何理解boost::regex的哪一部分未能匹配/search