Skip to content

Commit

Permalink
tg_cpphost: RegEXHandler: Add i flag (case insensitive)
Browse files Browse the repository at this point in the history
- Also switch to POSIX extended RegEX format
  • Loading branch information
Royna2544 committed Nov 21, 2023
1 parent ebf11ac commit 1a4ff81
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/RegEXHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ struct RegEXContext {
bool global;
};

using std::regex_constants::format_sed;
using std::regex_constants::extended;
using std::regex_constants::format_first_only;
using std::regex_constants::format_sed;
using std::regex_constants::icase;
using std::regex_constants::match_not_null;

static std::string doRegex(const RegEXContext* ctx, const std::string& text) {
Expand All @@ -26,24 +28,32 @@ static std::string doRegex(const RegEXContext* ctx, const std::string& text) {
}

void processRegEXCommand(const Bot& bot, const Message::Ptr& msg) {
static std::regex kSedCommandRegex(R"(s\/.+\/.+(\/g)?)");
// Matches sed command with subsitute command and g or i flags
static std::regex kSedCommandRegex(R"(s\/.+\/.+(\/(g|i|ig|gi))?)");
std::string& text = msg->text;
if (std::regex_match(text, kSedCommandRegex)) {
if (msg->replyToMessage && !msg->replyToMessage->text.empty()) {
auto vec = StringTools::split(text, '/');
if (vec.size() == 3 || vec.size() == 4) {
struct RegEXContext ctx {};
auto flags = extended;

if (vec.size() == 4) {
const auto& opt = vec[3];
// Due to the above regex match, it should be either none, i, g, ig, gi
ctx.global = opt.find('g') != std::string::npos;
if (opt.find('i') != std::string::npos)
flags |= icase;
}
try {
ctx.src = std::regex(vec[1]);
ctx.src = std::regex(vec[1], flags);
} catch (const std::regex_error& e) {
bot_sendReplyMessage(bot, msg, "Failed to parse regex (if it is) in '" + vec[1] + "': " + e.what());
return;
}

ctx.dest = vec[2];
ctx.global = vec.size() == 4 && vec[3] == "g";
LOG_D("src: '%s' dest: '%s' global: %d", vec[1].c_str(), vec[2].c_str(), ctx.global);
LOG_D("src: '%s' dest: '%s' global: %d icase: %d", vec[1].c_str(), vec[2].c_str(),
ctx.global, flags & icase);
try {
auto result = doRegex(&ctx, msg->replyToMessage->text);
bot_sendReplyMessage(bot, msg->replyToMessage, result);
Expand Down

0 comments on commit 1a4ff81

Please sign in to comment.