Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++ source code to match regular expressions using iterators by boost.
/*
* Matching regular expressions using iterators by boost.
*/
#include <iostream>
#include <string>
#include <boost/regex.hpp> // require "boost-regex-dev"
using namespace std;
/*
* [CLASS] Process
*/
class Proc
{
// Private Declaration
string sSrcC, sPtnC; // Source string, Regex pattern (char)
string sSrcW, sPtnW; // Source string, Regex pattern (wchar)
boost::regex reC, reW; // Regular expression
bool regexIterator(string, boost::regex); // Iterator matching
public:
Proc(); // Constructor
bool execMain(); // Main Process
};
/*
* Proc - Constructor
*/
Proc::Proc()
{
// Initial settings
sSrcC = "RedHatEnterpriseLinux CentOS ScientificLinux Fedora VineLinux";
sSrcW = "レッドハットリナックス セントオーエス サイエンティフィックリナックス ヴァインリナックス";
reC = "([^ ]+)Linux";
reW = "([^ ]+)リナックス";
}
/*
* Main Process
*/
bool Proc::execMain()
{
try {
// Iterator matching (char)
if (!regexIterator(sSrcC, reC)) return false;
// Iterator matching (wchar)
if (!regexIterator(sSrcW, reW)) return false;
} catch (char *e) {
cerr << "[EXCEPTION] " << e << endl;
return false;
}
return true;
}
// Iterator matching
bool Proc::regexIterator(string sSrc, boost::regex re)
{
try {
cout << "[Source string] " << sSrc << "\n"
<< "[Regex pattern] " << re << endl;
boost::sregex_iterator iter(sSrc.begin(), sSrc.end(), re);
boost::sregex_iterator last;
if (iter->size() == 0) {
cout << "[ Unmatched ]" << endl;
} else {
cout << "[ Matched ]" << endl;
while (iter != last) {
for (size_t i = 0; i < iter->size(); ++i) {
cout << i << ':' << iter->position(i) << ','
<< iter->length(i) << ':'
<< iter->str(i) << ' ';
}
cout << endl;
++iter;
}
}
} 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
You can’t perform that action at this time.