partial_regex_match.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 partial_regex_match.cpp
  14. * VERSION see <boost/version.hpp>
  15. * DESCRIPTION: regex_match example using partial matches.
  16. */
  17. #include <boost/regex.hpp>
  18. #include <string>
  19. #include <iostream>
  20. boost::regex e("(\\d{3,4})[- ]?(\\d{4})[- ]?(\\d{4})[- ]?(\\d{4})");
  21. bool is_possible_card_number(const std::string& input)
  22. {
  23. //
  24. // return false for partial match, true for full match, or throw for
  25. // impossible match based on what we have so far...
  26. boost::match_results<std::string::const_iterator> what;
  27. if(0 == boost::regex_match(input, what, e, boost::match_default | boost::match_partial))
  28. {
  29. // the input so far could not possibly be valid so reject it:
  30. throw std::runtime_error("Invalid data entered - this could not possibly be a valid card number");
  31. }
  32. // OK so far so good, but have we finished?
  33. if(what[0].matched)
  34. {
  35. // excellent, we have a result:
  36. return true;
  37. }
  38. // what we have so far is only a partial match...
  39. return false;
  40. }
  41. int main(int argc, char* argv[])
  42. {
  43. try{
  44. std::string input;
  45. if(argc > 1)
  46. input = argv[1];
  47. else
  48. std::cin >> input;
  49. if(is_possible_card_number(input))
  50. {
  51. std::cout << "Matched OK..." << std::endl;
  52. }
  53. else
  54. std::cout << "Got a partial match..." << std::endl;
  55. }
  56. catch(const std::exception& e)
  57. {
  58. std::cout << e.what() << std::endl;
  59. }
  60. return 0;
  61. }