| 1 | // Copyright (c) 2010 Jeroen Habraken |
| 2 | // |
| 3 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 4 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 5 | |
| 6 | #include <boost/spirit/include/qi.hpp> |
| 7 | |
| 8 | #include <iostream> |
| 9 | #include <ostream> |
| 10 | #include <string> |
| 11 | |
| 12 | namespace client |
| 13 | { |
| 14 | namespace qi = boost::spirit::qi; |
| 15 | |
| 16 | template <typename InputIterator> |
| 17 | struct unescaped_string |
| 18 | : qi::grammar<InputIterator, std::string(char const*)> |
| 19 | { |
| 20 | unescaped_string() |
| 21 | : unescaped_string::base_type(unesc_str) |
| 22 | { |
| 23 | unesc_char.add("\\a" , '\a')("\\b" , '\b')("\\f" , '\f')("\\n" , '\n') |
| 24 | ("\\r" , '\r')("\\t" , '\t')("\\v" , '\v')("\\\\" , '\\') |
| 25 | ("\\\'" , '\'')("\\\"" , '\"') |
| 26 | ; |
| 27 | |
| 28 | unesc_str = qi::lit(qi::_r1) |
| 29 | >> *(unesc_char | qi::alnum | "\\x" >> qi::hex) |
| 30 | >> qi::lit(qi::_r1) |
| 31 | ; |
| 32 | } |
| 33 | |
| 34 | qi::rule<InputIterator, std::string(char const*)> unesc_str; |
| 35 | qi::symbols<char const, char const> unesc_char; |
| 36 | }; |
| 37 | |
| 38 | } |
| 39 | |
| 40 | /////////////////////////////////////////////////////////////////////////////// |
| 41 | // Main program |
| 42 | /////////////////////////////////////////////////////////////////////////////// |
| 43 | int main() |
| 44 | { |
| 45 | namespace qi = boost::spirit::qi; |
| 46 | |
| 47 | typedef std::string::const_iterator iterator_type; |
| 48 | |
| 49 | std::string parsed; |
| 50 | |
| 51 | std::string str("'''string\\x20to\\x20unescape\\x3a\\x20\\n\\r\\t\\\"\\'\\x41'''" ); |
| 52 | char const* quote = "'''" ; |
| 53 | |
| 54 | iterator_type iter = str.begin(); |
| 55 | iterator_type end = str.end(); |
| 56 | |
| 57 | client::unescaped_string<iterator_type> p; |
| 58 | if (!qi::parse(first&: iter, last: end, expr: p(quote), attr&: parsed)) |
| 59 | { |
| 60 | std::cout << "-------------------------\n" ; |
| 61 | std::cout << "Parsing failed\n" ; |
| 62 | std::cout << "-------------------------\n" ; |
| 63 | } |
| 64 | else |
| 65 | { |
| 66 | std::cout << "-------------------------\n" ; |
| 67 | std::cout << "Parsed: " << parsed << "\n" ; |
| 68 | std::cout << "-------------------------\n" ; |
| 69 | } |
| 70 | |
| 71 | return 0; |
| 72 | } |
| 73 | |