regex_match_example.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. *
  3. * Copyright (c) 1998-2002
  4. * John Maddock
  5. *
  6. * Use, modification and distribution are subject to the
  7. * Boost Software License, Version 1.0. (See accompanying file
  8. * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. *
  10. */
  11. /*
  12. * LOCATION: see http://www.boost.org for most recent version.
  13. * FILE regex_match_example.cpp
  14. * VERSION see <boost/version.hpp>
  15. * DESCRIPTION: ftp based regex_match example.
  16. */
  17. #include <boost/regex.hpp>
  18. #include <cstdlib>
  19. #include <stdlib.h>
  20. #include <string>
  21. #include <iostream>
  22. using namespace std;
  23. using namespace boost;
  24. regex expression("^([0-9]+)(\\-| |$)(.*)$");
  25. // process_ftp:
  26. // on success returns the ftp response code, and fills
  27. // msg with the ftp response message.
  28. int process_ftp(const char* response, std::string* msg)
  29. {
  30. cmatch what;
  31. if(regex_match(response, what, expression))
  32. {
  33. // what[0] contains the whole string
  34. // what[1] contains the response code
  35. // what[2] contains the separator character
  36. // what[3] contains the text message.
  37. if(msg)
  38. msg->assign(what[3].first, what[3].second);
  39. return ::atoi(what[1].first);
  40. }
  41. // failure did not match
  42. if(msg)
  43. msg->erase();
  44. return -1;
  45. }
  46. #if defined(BOOST_MSVC) || (defined(__BORLANDC__) && (__BORLANDC__ == 0x550))
  47. //
  48. // problem with std::getline under MSVC6sp3
  49. istream& getline(istream& is, std::string& s)
  50. {
  51. s.erase();
  52. char c = static_cast<char>(is.get());
  53. while(c != '\n')
  54. {
  55. s.append(1, c);
  56. c = static_cast<char>(is.get());
  57. }
  58. return is;
  59. }
  60. #endif
  61. int main(int argc, const char*[])
  62. {
  63. std::string in, out;
  64. do
  65. {
  66. if(argc == 1)
  67. {
  68. cout << "enter test string" << endl;
  69. getline(cin, in);
  70. if(in == "quit")
  71. break;
  72. }
  73. else
  74. in = "100 this is an ftp message text";
  75. int result;
  76. result = process_ftp(in.c_str(), &out);
  77. if(result != -1)
  78. {
  79. cout << "Match found:" << endl;
  80. cout << "Response code: " << result << endl;
  81. cout << "Message text: " << out << endl;
  82. }
  83. else
  84. {
  85. cout << "Match not found" << endl;
  86. }
  87. cout << endl;
  88. } while(argc == 1);
  89. return 0;
  90. }