|
| 1 | +Examples |
| 2 | +======== |
| 3 | + |
| 4 | +Extracting a number from input |
| 5 | +------------------------------ |
| 6 | +:: |
| 7 | + |
| 8 | + std::optional<std::string_view> extract_number(std::string_view s) noexcept { |
| 9 | + if (auto m = ctre::match<"[a-z]+([0-9]+)">(s)) { |
| 10 | + return m.get<1>().to_view(); |
| 11 | + } else { |
| 12 | + return std::nullopt; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | +`link to compiler explorer <https://gcc.godbolt.org/z/5U67_e>`_ |
| 17 | + |
| 18 | +Extracting values from date |
| 19 | +--------------------------- |
| 20 | +:: |
| 21 | + |
| 22 | + |
| 23 | + struct date { std::string_view year; std::string_view month; std::string_view day; }; |
| 24 | + std::optional<date> extract_date(std::string_view s) noexcept { |
| 25 | + using namespace ctre::literals; |
| 26 | + if (auto [whole, year, month, day] = ctre::match<"(\\d{4})/(\\d{1,2})/(\\d{1,2})">(s); whole) { |
| 27 | + return date{year, month, day}; |
| 28 | + } else { |
| 29 | + return std::nullopt; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + //static_assert(extract_date("2018/08/27"sv).has_value()); |
| 34 | + //static_assert((*extract_date("2018/08/27"sv)).year == "2018"sv); |
| 35 | + //static_assert((*extract_date("2018/08/27"sv)).month == "08"sv); |
| 36 | + //static_assert((*extract_date("2018/08/27"sv)).day == "27"sv); |
| 37 | + |
| 38 | +`link to compiler explorer <https://gcc.godbolt.org/z/x64CVp>`_ |
| 39 | + |
| 40 | +Lexer |
| 41 | +----- |
| 42 | +:: |
| 43 | + |
| 44 | + enum class type { |
| 45 | + unknown, identifier, number |
| 46 | + }; |
| 47 | + |
| 48 | + struct lex_item { |
| 49 | + type t; |
| 50 | + std::string_view c; |
| 51 | + }; |
| 52 | + |
| 53 | + std::optional<lex_item> lexer(std::string_view v) noexcept { |
| 54 | + if (auto [m,id,num] = ctre::match<"([a-z]+)|([0-9]+)">(v); m) { |
| 55 | + if (id) { |
| 56 | + return lex_item{type::identifier, id}; |
| 57 | + } else if (num) { |
| 58 | + return lex_item{type::number, num}; |
| 59 | + } |
| 60 | + } |
| 61 | + return std::nullopt; |
| 62 | + } |
| 63 | + |
| 64 | +`link to compiler explorer <https://gcc.godbolt.org/z/PKTiCC>`_ |
| 65 | + |
| 66 | +Range over input |
| 67 | +---------------- |
| 68 | + |
| 69 | +This support is preliminary and probably the API will be changed. |
| 70 | + |
| 71 | +:: |
| 72 | + |
| 73 | + auto input = "123,456,768"sv; |
| 74 | + |
| 75 | + for (auto match: ctre::range<"([0-9]+),?">(input)) { |
| 76 | + std::cout << std::string_view{match.get<0>()} << "\n"; |
| 77 | + } |
0 commit comments