我有一些由空格分隔的文本。
有点像 123 10.03.1 TEXT1 TEXT2 TEXT3 TEXT4 TEXT5 TEXT6 2015/10/10 2012.
我能够得到不是“TEXT1 TEXT2 TEXT3 TEXT4 TEXT5 TEXT6”的所有内容我想为该文本重复捕获组:
TEXT1 TEXT2 TEXT3 TEXT4 TEXT5 TEXT6
我想重复捕获组,比如。
(\s*\w)*
但我想忽略空格 有没有办法忽略正则表达式中的空格?
我将使用 boost::regex_search 来获取捕获组。 有没有办法存档,我尝试在捕获组上使用“?:”,但可能我遗漏了一些东西。
最佳答案
我强烈怀疑您想要能够解析语法的东西;这是 Boost Spirit X3:
#include <boost/spirit/home/x3.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <boost/fusion/adapted/boost_tuple.hpp>
#include <iostream>
namespace std {
// hack for debug output
std::ostream& operator<<(std::ostream& os, std::vector<std::string> const& v) {
for (auto i = 0ul; i<v.size(); ++i) {
if (i) os << " ";
os << v[i];
}
return os;
}
}
namespace x3 = boost::spirit::x3;
int main() {
std::string const input = "123 10.03.1 TEXT1 TEXT2 TEXT3 TEXT4 TEXT5 \t \tTEXT6 2015/10/10 \t 2012";
int num;
std::string version;
std::vector<std::string> texts;
std::string date;
int year;
auto attr = boost::tie(num, version, texts, date, year);
bool ok = false;
{
using namespace x3;
auto date_ = raw [ repeat(4) [ digit ] >> '/' >> repeat(2) [ digit ] >> '/' >> repeat(2) [ digit ] ];
auto version_ = lexeme [ +char_("0-9.") ];
auto text_ = lexeme [ alpha >> *alnum ];
ok = phrase_parse(input.begin(), input.end(),
int_ >> version_ >> *text_ >> date_ >> int_ /* >> eoi */,
x3::space,
attr);
}
if (ok) {
std::cout << "parsed: " << attr << "\n";
} else {
std::cout << "parse failed\n";
}
}
打印
parsed: (123 10.03.1 TEXT1 TEXT2 TEXT3 TEXT4 TEXT5 TEXT6 2015/10/10 2012)
请注意这不仅仅是拆分您的输入。它在需要时忽略空格,将转换后的值分配给整数,将 TEXTn
元素放入向量等。
如果您愿意,您也可以从流中解析这些(参见 boost::spirit::istream_iterator
)。
关于regex - 重复捕获组忽略空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33392279/