credit_card_example.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 credit_card_example.cpp
  14. * VERSION see <boost/version.hpp>
  15. * DESCRIPTION: Credit card number formatting code.
  16. */
  17. #include <boost/regex.hpp>
  18. #include <string>
  19. bool validate_card_format(const std::string& s)
  20. {
  21. static const boost::regex e("(\\d{4}[- ]){3}\\d{4}");
  22. return boost::regex_match(s, e);
  23. }
  24. const boost::regex e("\\A(\\d{3,4})[- ]?(\\d{4})[- ]?(\\d{4})[- ]?(\\d{4})\\z");
  25. const std::string machine_format("\\1\\2\\3\\4");
  26. const std::string human_format("\\1-\\2-\\3-\\4");
  27. std::string machine_readable_card_number(const std::string& s)
  28. {
  29. return boost::regex_replace(s, e, machine_format, boost::match_default | boost::format_sed);
  30. }
  31. std::string human_readable_card_number(const std::string& s)
  32. {
  33. return boost::regex_replace(s, e, human_format, boost::match_default | boost::format_sed);
  34. }
  35. #include <iostream>
  36. using namespace std;
  37. int main()
  38. {
  39. string s[4] = { "0000111122223333", "0000 1111 2222 3333",
  40. "0000-1111-2222-3333", "000-1111-2222-3333", };
  41. int i;
  42. for(i = 0; i < 4; ++i)
  43. {
  44. cout << "validate_card_format(\"" << s[i] << "\") returned " << validate_card_format(s[i]) << endl;
  45. }
  46. for(i = 0; i < 4; ++i)
  47. {
  48. cout << "machine_readable_card_number(\"" << s[i] << "\") returned " << machine_readable_card_number(s[i]) << endl;
  49. }
  50. for(i = 0; i < 4; ++i)
  51. {
  52. cout << "human_readable_card_number(\"" << s[i] << "\") returned " << human_readable_card_number(s[i]) << endl;
  53. }
  54. return 0;
  55. }