unescaped_string.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include <boost/spirit/include/qi.hpp>
  6. #include <iostream>
  7. #include <ostream>
  8. #include <string>
  9. namespace client
  10. {
  11. namespace qi = boost::spirit::qi;
  12. template <typename InputIterator>
  13. struct unescaped_string
  14. : qi::grammar<InputIterator, std::string(char const*)>
  15. {
  16. unescaped_string()
  17. : unescaped_string::base_type(unesc_str)
  18. {
  19. unesc_char.add("\\a", '\a')("\\b", '\b')("\\f", '\f')("\\n", '\n')
  20. ("\\r", '\r')("\\t", '\t')("\\v", '\v')("\\\\", '\\')
  21. ("\\\'", '\'')("\\\"", '\"')
  22. ;
  23. unesc_str = qi::lit(qi::_r1)
  24. >> *(unesc_char | qi::alnum | "\\x" >> qi::hex)
  25. >> qi::lit(qi::_r1)
  26. ;
  27. }
  28. qi::rule<InputIterator, std::string(char const*)> unesc_str;
  29. qi::symbols<char const, char const> unesc_char;
  30. };
  31. }
  32. ///////////////////////////////////////////////////////////////////////////////
  33. // Main program
  34. ///////////////////////////////////////////////////////////////////////////////
  35. int main()
  36. {
  37. namespace qi = boost::spirit::qi;
  38. typedef std::string::const_iterator iterator_type;
  39. std::string parsed;
  40. std::string str("'''string\\x20to\\x20unescape\\x3a\\x20\\n\\r\\t\\\"\\'\\x41'''");
  41. char const* quote = "'''";
  42. iterator_type iter = str.begin();
  43. iterator_type end = str.end();
  44. client::unescaped_string<iterator_type> p;
  45. if (!qi::parse(iter, end, p(quote), parsed))
  46. {
  47. std::cout << "-------------------------\n";
  48. std::cout << "Parsing failed\n";
  49. std::cout << "-------------------------\n";
  50. }
  51. else
  52. {
  53. std::cout << "-------------------------\n";
  54. std::cout << "Parsed: " << parsed << "\n";
  55. std::cout << "-------------------------\n";
  56. }
  57. return 0;
  58. }