Regex C++:提取标记之间的子字符串

Regex C++: extract substring between tags

本文关键字:之间 字符串 C++ 提取 Regex      更新时间:2023-10-16

我想在两个标签之间提取一些子字符串。示例:<column r="1"><t b="red"><v>1</v></t></column>我想得到:<t b="red"><v>1</v></t>

我不想使用boost或其他libs。只是C++中的标准内容,除了CERN的ROOT-lib,还有TRegexp,但我不知道如何使用它…

您不应该使用正则表达式来尝试匹配html,但是,对于这种特殊情况,您可以执行以下操作:

#include <string>
#include <regex>
// Your string
std::string str = "<column r="1"><t b="red"><v>1</v></t></column>";
// Your regex, in this specific scenario
// Will NOT work for nested <column> tags!
std::regex rgx("<column.*?>(.*?)</column>");
std::smatch match;
// Try to match it
if(std::regex_search(str.begin(), str.end(), match, rgx)) {
  // You can use `match' here to get your substring
};

正如安东上面所说:不要。