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