主題:
use c++ regex parse string enclosed in double quote難處:
考慮 escaped quote範例:
如果是 std::string s = "\"\\\"aaa\"\"bbb\""; 要 parse 成 \"aaa & bbb以下我直接貼 code, 後面註解是想要 parse 的結果
std::string s = "\"\\\\\"aaa\"\"bbb\""; // \\"aaa & bbb
std::string s = "\"aa\\\"a\" \"bbb\""; // aa\"a & bbb
std::string s = "\"aa\\\\\"a\" \"bbb\""; // aa\\"a & bbb
std::string s = "\"\"\"aaa\"\t \"bbb\""; // empty & aaa & bbb
怎麼寫:
std::regex e ("\"((([^\\\\]*\\\\.)|([^\"]*))*)\"");std::smatch sm;
std::string line = s;
while (std::regex_search (line, sm, e)) {
std::cout << "range with " << sm.size() << " matches\n";
std::cout << "the matches were: ";
for (unsigned i=0; i<sm.size(); ++i) {
std::cout << "[" << sm[i] << "] ";
}
line = sm.suffix().str();
std::cout << std::endl << "line: " << line;
std::cout << std::endl;
}
// 裡面印出的 sm[1] 就是我們想要的結果
參考:
http://stackoverflow.com/questions/21658860/how-to-use-regex-chttp://www.cplusplus.com/reference/regex/match_results/suffix/
http://stackoverflow.com/questions/6863518/regex-match-one-of-two-words
http://stackoverflow.com/questions/249791/regex-for-quoted-string-with-escaping-quotes (Guy BedFord 的寫法再改良)
沒有留言:
張貼留言