captures_example.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. *
  3. * Copyright (c) 2003-2004
  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 captures_example.cpp
  14. * VERSION see <boost/version.hpp>
  15. * DESCRIPTION: Demonstrate the behaviour of captures.
  16. */
  17. #include <boost/regex.hpp>
  18. #include <iostream>
  19. void print_captures(const std::string& regx, const std::string& text)
  20. {
  21. boost::regex e(regx);
  22. boost::smatch what;
  23. std::cout << "Expression: \"" << regx << "\"\n";
  24. std::cout << "Text: \"" << text << "\"\n";
  25. if(boost::regex_match(text, what, e, boost::match_extra))
  26. {
  27. unsigned i, j;
  28. std::cout << "** Match found **\n Sub-Expressions:\n";
  29. for(i = 0; i < what.size(); ++i)
  30. std::cout << " $" << i << " = \"" << what[i] << "\"\n";
  31. std::cout << " Captures:\n";
  32. for(i = 0; i < what.size(); ++i)
  33. {
  34. std::cout << " $" << i << " = {";
  35. for(j = 0; j < what.captures(i).size(); ++j)
  36. {
  37. if(j)
  38. std::cout << ", ";
  39. else
  40. std::cout << " ";
  41. std::cout << "\"" << what.captures(i)[j] << "\"";
  42. }
  43. std::cout << " }\n";
  44. }
  45. }
  46. else
  47. {
  48. std::cout << "** No Match found **\n";
  49. }
  50. }
  51. int main(int , char* [])
  52. {
  53. print_captures("(([[:lower:]]+)|([[:upper:]]+))+", "aBBcccDDDDDeeeeeeee");
  54. print_captures("a(b+|((c)*))+d", "abd");
  55. print_captures("(.*)bar|(.*)bah", "abcbar");
  56. print_captures("(.*)bar|(.*)bah", "abcbah");
  57. print_captures("^(?:(\\w+)|(?>\\W+))*$", "now is the time for all good men to come to the aid of the party");
  58. print_captures("^(?>(\\w+)\\W*)*$", "now is the time for all good men to come to the aid of the party");
  59. print_captures("^(\\w+)\\W+(?>(\\w+)\\W+)*(\\w+)$", "now is the time for all good men to come to the aid of the party");
  60. print_captures("^(\\w+)\\W+(?>(\\w+)\\W+(?:(\\w+)\\W+){0,2})*(\\w+)$", "now is the time for all good men to come to the aid of the party");
  61. return 0;
  62. }