Created
November 12, 2018 05:28
-
-
Save jacobkahn/a280d1e82cd9812a0d6194b5910593b0 to your computer and use it in GitHub Desktop.
C++-compatible regex replace with only glibc regex.h
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(®ex, 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(®ex, curr, 0, NULL, 0)) != REG_NOMATCH) { | |
if (ret || regexec(®ex, 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(®ex); | |
delete[] inBuffer; | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment