c++ - std::smatch str() 没有返回正确的字符串
问题描述
我决定制作自己的 regex.h,其中包含一个带有一些方法的类,以便更轻松地检查和使用正则表达式解析字符串。
我的 .h 的第一个版本只包含一些方法,效果很好。后来,我决定将所有这些方法组织在一个类中,一切正常,但是,在某些时候,“match_str”方法开始返回长度正确的字符串,但只包含“|” 字符,出于某种原因。
这是整个 regex.h 文件:
#include <string>
#include <regex>
#include <vector>
class regex {
std::vector<std::smatch> match;
public:
regex(std::string);
std::regex r;
int generate_matches(std::string s) {
auto matches_begin = std::sregex_iterator(s.begin(), s.end(), r);
auto matches_end = std::sregex_iterator();
for (std::sregex_iterator i = matches_begin; i != matches_end; ++i) { match.push_back(*i); }
return match.size();
}
bool matches(std::string s) {
return std::regex_search(s, r);
}
int match_count() {
return match.size();
}
std::string match_str(int index = 0, int group = 0) {
return match.size() ? match.at(index)[group].str() : "";
}
int match_pos(int index = 0) {
return match.at(index).position() + 1;
}
}; regex::regex(std::string regex) : r(regex) {}
除了“match_str”方法之外的所有东西似乎都可以正常工作
这段代码:
int main() {
regex rx("(int|long)( +)([a-z]);");
if (rx.generate_matches("int a; int b; int c;")) {
std::cout << rx.match_str() + "\n";
}
system("pause");
}
输出:
¦¦¦¦¦¦
Press any key to continue . . .
解决方案
match_results
保持对象const iterator
或const char*
指向匹配字符串的指针。在generate_matches
字符串s
中,对象是局部变量,因此在函数终止时将其删除,您不能将 const 迭代器或局部变量的指针存储到向量 - 您将有悬空指针,并且当您尝试读取被破坏的对象的数据时,这是未定义的行为。
您可以向您的类添加其他变量regex
并更改您的generate_matches
函数,如下所示:
class regex {
std::vector<std::smatch> match;
std::string str; // <---
int generate_matches(std::string s) {
str = s; // <---
auto matches_begin = std::sregex_iterator(str.begin(), str.end(), r); // <---
auto matches_end = std::sregex_iterator();
for (std::sregex_iterator i = matches_begin; i != matches_end; ++i) { match.push_back(*i); }
return match.size();
}
现在您可以调用match_str
函数并读取match
向量,因为smatch
对象引用现有对象 - str
,而不是临时对象。
推荐阅读
- sql - 如何在 Oracle 存储过程中传递时间戳值?
- robotframework - 使用反应组件上的机器人框架访问列表中项目的索引
- python - 使用 BeautifulSoup 遍历 HTML 以查找标签和字符串匹配
- android - 在 android 上具有多个图像的启动画面
- c++ - 选择排序程序未正确排序
- c# - 在超大文件中搜索(Open Academic Graph / Microsoft Academic Graph)
- javascript - 将保存在 HTML 中的图片显示到 Vue.js 页面中
- datatables - JQuery 数据表:卡中不是全尺寸
- javascript - UnhandledPromiseRejectionWarning:TypeError:无法在客户端读取未定义的属性“通道”。
- reactjs - 将 Redux 与 useEffect Hook 混合使用