quick.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 1998-2002 John Maddock
  2. // Copyright 2017 Peter Dimov
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. //
  6. // See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt
  8. // See library home page at http://www.boost.org/libs/regex
  9. #include <boost/regex.hpp>
  10. #include <boost/core/lightweight_test.hpp>
  11. #include <string>
  12. bool validate_card_format(const std::string& s)
  13. {
  14. static const boost::regex e("(\\d{4}[- ]){3}\\d{4}");
  15. return boost::regex_match(s, e);
  16. }
  17. const boost::regex card_rx("\\A(\\d{3,4})[- ]?(\\d{4})[- ]?(\\d{4})[- ]?(\\d{4})\\z");
  18. const std::string machine_format("\\1\\2\\3\\4");
  19. const std::string human_format("\\1-\\2-\\3-\\4");
  20. std::string machine_readable_card_number(const std::string& s)
  21. {
  22. return boost::regex_replace(s, card_rx, machine_format, boost::match_default | boost::format_sed);
  23. }
  24. std::string human_readable_card_number(const std::string& s)
  25. {
  26. return boost::regex_replace(s, card_rx, human_format, boost::match_default | boost::format_sed);
  27. }
  28. int main()
  29. {
  30. std::string s[ 4 ] = { "0000111122223333", "0000 1111 2222 3333", "0000-1111-2222-3333", "000-1111-2222-3333" };
  31. BOOST_TEST( !validate_card_format( s[0] ) );
  32. BOOST_TEST_EQ( machine_readable_card_number( s[0] ), s[0] );
  33. BOOST_TEST_EQ( human_readable_card_number( s[0] ), s[2] );
  34. BOOST_TEST( validate_card_format( s[1] ) );
  35. BOOST_TEST_EQ( machine_readable_card_number( s[1] ), s[0] );
  36. BOOST_TEST_EQ( human_readable_card_number( s[1] ), s[2] );
  37. BOOST_TEST( validate_card_format( s[2] ) );
  38. BOOST_TEST_EQ( machine_readable_card_number( s[2] ), s[0] );
  39. BOOST_TEST_EQ( human_readable_card_number( s[2] ), s[2] );
  40. BOOST_TEST( !validate_card_format( s[3] ) );
  41. return boost::report_errors();
  42. }