|
| 1 | +#include <expression.hpp> |
| 2 | + |
| 3 | +expression::expression(std::string regex, std::vector<std::string> arguments) |
| 4 | + : regex_(std::move(regex)), arguments_(std::move(arguments)) { |
| 5 | +} |
| 6 | + |
| 7 | +std::string expression::get_regex() const { |
| 8 | + return regex_; |
| 9 | +} |
| 10 | + |
| 11 | +std::vector<std::string> expression::get_arguments() const { |
| 12 | + return arguments_; |
| 13 | +} |
| 14 | + |
| 15 | +std::shared_ptr<expression_result> expression::query(const std::string &input) { |
| 16 | + std::unordered_map<std::string, std::string> _bindings; |
| 17 | + const std::regex _pattern(regex_); |
| 18 | + bool _matches = false; |
| 19 | + if (std::smatch _match; std::regex_match(input, _match, _pattern)) { |
| 20 | + _matches = true; |
| 21 | + auto _iterator = _match.begin(); |
| 22 | + ++_iterator; |
| 23 | + for (auto &_key: arguments_) { |
| 24 | + _bindings[_key] = *_iterator; |
| 25 | + ++_iterator; |
| 26 | + } |
| 27 | + } |
| 28 | + return std::make_shared<expression_result>(_matches, _bindings); |
| 29 | +} |
| 30 | + |
| 31 | +std::shared_ptr<expression> expression::from_string(const std::string &input) { |
| 32 | + std::size_t _open = input.find('{'); |
| 33 | + std::size_t _close = input.find('}'); |
| 34 | + std::size_t _position = 0; |
| 35 | + |
| 36 | + std::vector<std::string> _arguments; |
| 37 | + std::string _regex; |
| 38 | + |
| 39 | + if (_open == std::string::npos && _close == std::string::npos) |
| 40 | + return std::make_shared<expression>(std::string{input.data()}, _arguments); |
| 41 | + |
| 42 | + while (_open != std::string::npos && _close != std::string::npos) { |
| 43 | + _regex.append(input.substr(_position, _open - _position)); |
| 44 | + std::string _value{input.substr(_open + 1, _close - _open - 1)}; |
| 45 | + |
| 46 | + if (std::find(_arguments.begin(), _arguments.end(), _value) != _arguments.end()) |
| 47 | + throw std::runtime_error("groups can't be repeated ... "); |
| 48 | + |
| 49 | + _regex.append(R"(([a-zA-Z0-9\-_]+))"); |
| 50 | + _arguments.emplace_back(_value); |
| 51 | + |
| 52 | + _position = _close + 1; |
| 53 | + _open = input.find('{', _close); |
| 54 | + _close = input.find('}', _open); |
| 55 | + |
| 56 | + if (_open == std::string::npos && _close == std::string::npos && _position != input.size()) |
| 57 | + _regex.append(input.substr(_position, input.size() - _position)); |
| 58 | + } |
| 59 | + |
| 60 | + return std::make_shared<expression>(_regex, _arguments); |
| 61 | +} |
0 commit comments