[英]parsing text files using boost regular expressions
我正在嘗試使用boost::regex
庫在C ++中解析文本文件。
我正在嘗試將這一行解析為我的程序:1_3,1,3,0
你們知道寫什么匹配嗎?
我試過這個,但它不起作用:
boost::regex rgex("^([0-9]),([0-9]+),([0-9]+),([0-9]+).*");
提前致謝
我不會使用正則表達式,這使您不得不進行所有類型的轉換。
我將直接解析為結構的vector<>
struct record {
std::string name;
char x, y, cost;
};
和Boost Spirit一樣
std::vector<record> data;
bool ok = qi::phrase_parse(f, l,
(qi::lexeme[+~qi::char_(',')] >> ',' >> qi::int_ >> ',' >> qi::int_ >> ',' >> qi::int_) % qi::eol,
qi::blank,
data);
if (ok)
{
std::cout << "Parsed success: " << data.size() << " records\n";
for(auto& r : data)
std::cout << r << "\n";
}
請注意,此方法接受並忽略額外的空格( qi::blank
)。
看到Live On Coliru打印:
Parsed success: 11 records
1_3 1 3 0
16_92 16 92 76
8_31 8 31 13
3_45 3 45 46
12_67 12 67 66
17_27 17 27 2
7_72 7 72 74
0_36 0 36 25
18_30 18 30 50
6_35 6 35 19
16_5 16 5 50
以供參考
#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
struct record {
std::string name;
char x, y, cost;
friend std::ostream& operator<<(std::ostream& os,const record& r) {
return os << r.name << "\t" << int(r.x) << "\t" << int(r.y) << "\t" << int(r.cost);
}
};
BOOST_FUSION_ADAPT_STRUCT(record, (std::string, name)(char, x)(char, y)(char, cost))
int main()
{
std::istringstream iss(
"1_3,1,3,0\n"
"16_92,16,92,76\n"
"8_31,8,31,13\n"
"3_45,3,45,46\n"
"12_67,12,67,66\n"
"17_27,17,27,2\n"
"7_72,7,72,74\n"
"0_36,0,36,25\n"
"18_30,18,30,50\n"
"6_35,6,35,19\n"
"16_5,16,5,50"
);
boost::spirit::istream_iterator f(iss >> std::noskipws), l;
std::vector<record> data;
bool ok = qi::phrase_parse(f, l,
(qi::lexeme[+~qi::char_(',')]
>> ',' >> qi::int_ >> ',' >> qi::int_ >> ',' >> qi::int_
) % qi::eol,
qi::blank,
data);
if (ok)
{
std::cout << "Parsed success: " << data.size() << " records\n";
for(auto& r : data)
std::cout << r << "\n";
} else
{
std::cout << "Parse failed\n";
}
if (f!=l)
{
std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}
}
在不知道所有可接受的字符的情況下,解析該行的最簡單方法是用逗號分隔。
"^([^,]+),([^,]+),([^,]+),(.+)$"
[^,]
表示任何非逗號字符。 [^,]+
表示1個或多個非逗號字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.