diff --git a/highlighter.cpp b/highlighter.cpp new file mode 100644 index 0000000..aa54ee5 --- /dev/null +++ b/highlighter.cpp @@ -0,0 +1,50 @@ +#include "highlighter.h" +#include +#include + +std::string Highlighter::highlight_text( + const std::string& text, + const std::vector& keywords, + const std::string& pre_tag, + const std::string& post_tag +) { + auto spans = find_keyword_positions(text, keywords); + std::string result = text; + + // 从后向前插入标签,避免位置偏移 + std::sort(spans.begin(), spans.end(), + [](const HighlightSpan& a, const HighlightSpan& b) { + return a.start > b.start; + }); + + for (const auto& span : spans) { + result.insert(span.start + span.length, post_tag); + result.insert(span.start, pre_tag); + } + + return result; +} + +std::vector Highlighter::find_keyword_positions( + const std::string& text, + const std::vector& keywords +) { + std::vector spans; + + for (const auto& keyword : keywords) { + std::regex word_regex(keyword, std::regex::icase); + auto words_begin = std::sregex_iterator( + text.begin(), text.end(), word_regex + ); + auto words_end = std::sregex_iterator(); + + for (auto i = words_begin; i != words_end; ++i) { + spans.push_back({ + static_cast(i->position()), + static_cast(i->length()) + }); + } + } + + return spans; +} \ No newline at end of file