diff --git a/include/maddy/callbackreplacer.h b/include/maddy/callbackreplacer.h new file mode 100644 index 0000000..fb24e72 --- /dev/null +++ b/include/maddy/callbackreplacer.h @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. For more information see the + * LICENSE file. + */ +#pragma once + +#include +#include +#include + +namespace maddy { + +inline std::string regex_callback_replacer(std::regex ®ex, const std::string &input, + std::function &callback) +{ + std::string result; + auto tagsbegin = std::sregex_iterator(input.begin(), input.end(), regex); + auto tagsend = std::sregex_iterator(); + auto matchbegin = 0; + for(std::sregex_iterator i = tagsbegin; i != tagsend; ++i) + { + std::smatch match = *i; + + auto matchlength = match.length(0); + auto matchpos = match.position(); + + result += input.substr(matchbegin, matchpos - matchbegin); + result += callback(match); + matchbegin = matchpos + matchlength; + } + result += input.substr(matchbegin); + return result; +} + +} + diff --git a/include/maddy/linkparser.h b/include/maddy/linkparser.h index e382f21..79ca390 100644 --- a/include/maddy/linkparser.h +++ b/include/maddy/linkparser.h @@ -10,6 +10,7 @@ #include #include "maddy/lineparser.h" +#include "maddy/callbackreplacer.h" // ----------------------------------------------------------------------------- @@ -26,6 +27,16 @@ namespace maddy { */ class LinkParser : public LineParser { +private: + std::function callback = [](std::smatch & match){ + std::string inner = match.str(1); + std::string link = match.str(2); + return "" + inner + ""; + }; + + std::regex re = std::regex("\\[([^\\]]*)\\]\\(([^\\]]*)\\)"); + + public: /** * Parse @@ -41,10 +52,12 @@ public: void Parse(std::string& line) override { - static std::regex re("\\[([^\\]]*)\\]\\(([^\\]]*)\\)"); - static std::string replacement = "$1"; + line = regex_callback_replacer(re,line,callback); + } - line = std::regex_replace(line, re, replacement); + void setCallback(std::function callback) + { + this->callback = callback; } }; // class LinkParser