Skip to content

Instantly share code, notes, and snippets.

@jacobkahn
Created November 12, 2018 05:28
Show Gist options
  • Save jacobkahn/a280d1e82cd9812a0d6194b5910593b0 to your computer and use it in GitHub Desktop.
Save jacobkahn/a280d1e82cd9812a0d6194b5910593b0 to your computer and use it in GitHub Desktop.
C++-compatible regex replace with only glibc regex.h
#include <regex.h>
std::string regexReplace(
const std::string& inStr,
const std::string& regexStr,
const std::string& repl) {
int ret = 0;
// Create expr
regex_t regex;
if ((ret = regcomp(&regex, regexStr.c_str(), REG_EXTENDED))) {
throw std::runtime_error("regcomp: Cannot compile regular expression.");
}
// In string to buffer
const char* inCSTr = inStr.c_str();
const std::string::size_type inSize = inStr.size();
char* inBuffer = new char[inSize + 1];
memcpy(inBuffer, inCSTr, inSize + 1);
// Running output buffer
std::string out;
// Replace
regmatch_t pmatch[1];
char* curr = inBuffer;
while ((ret = regexec(&regex, curr, 0, NULL, 0)) != REG_NOMATCH) {
if (ret || regexec(&regex, curr, 1, pmatch, 0)) {
throw std::runtime_error("regexec: Error finding regex matches.");
};
regoff_t startOffset = pmatch[0].rm_so;
regoff_t endOffset = pmatch[0].rm_eo;
// Append unmatched substring and repl
out += std::string(curr, startOffset);
out += repl;
curr += endOffset;
}
// Remaining unmatched chars
out += std::string(curr);
regfree(&regex);
delete[] inBuffer;
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment