Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created August 14, 2014 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/23a5c9a18abb0f21a280 to your computer and use it in GitHub Desktop.
Save komasaru/23a5c9a18abb0f21a280 to your computer and use it in GitHub Desktop.
C++ source code to replace regular expressions by boost.
/*
* Replacement of regular expressions by boost.
*/
#include <iostream>
#include <string>
#include <boost/regex.hpp> // require "boost-regex-dev"
using namespace std;
/*
* [CLASS] Process
*/
class Proc
{
// Private Declaration
string sSrc; // Source string
string sFmtA, sFmtS; // Replace string (All, Sub)
boost::regex reA, reS; // Regular expression (All, Sub)
string result; // Result
bool regexReplaceA(string, boost::regex, string); // All replace
bool regexReplaceS(string, boost::regex, string); // Sub replace
public:
Proc(); // Constructor
bool execMain(); // Main Process
};
/*
* Proc - Constructor
*/
Proc::Proc()
{
// Initial settings
sSrc = "RedHatEnterpriseリナックス CentOS サイエンティフィックLinux Fedora VineLinux";
reA = "Linux"; // All matching - Regular expression
sFmtA = "リナックス"; // All matching - Replace string
reS = "([^ ]+)(Linux)"; // Sub matching - Regular expression
sFmtS = "(?1****)(?2リナックス)"; // Sub matching - Replace string
}
/*
* Main Process
*/
bool Proc::execMain()
{
try {
// Replace (All match)
if (!regexReplaceA(sSrc, reA, sFmtA)) return false;
// Replace (Sub match)
if (!regexReplaceS(sSrc, reS, sFmtS)) return false;
} catch (char *e) {
cerr << "[EXCEPTION] " << e << endl;
return false;
}
return true;
}
// Replace (All match)
bool Proc::regexReplaceA(string sSrc, boost::regex re, string sFmt)
{
try {
cout << "[Source string]\n " << sSrc << "\n"
<< "[Replace]\n " << re << " -> "
<< sFmt << endl;
result = boost::regex_replace(sSrc, re, sFmt);
cout << "[Result]\n " << result << endl;
} catch (char *e) {
cerr << "[EXCEPTION] " << e << endl;
return false;
}
cout << endl;
return true;
}
// Replace (Sub match)
bool Proc::regexReplaceS(string sSrc, boost::regex re, string sFmt)
{
try {
cout << "[Source string]\n " << sSrc << "\n"
<< "[Replace]\n " << re << " -> "
<< sFmt << endl;
result = boost::regex_replace(
sSrc, re, sFmt, boost::match_default | boost::format_all
);
cout << "[Result]\n " << result << endl;
} catch (char *e) {
cerr << "[EXCEPTION] " << e << endl;
return false;
}
cout << endl;
return true;
}
/*
* Execution
*/
int main(){
try {
Proc objMain;
bool bRet = objMain.execMain();
if (!bRet) cout << "ERROR!" << endl;
} catch (char *e) {
cerr << "[EXCEPTION] " << e << endl;
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment