Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created August 14, 2014 07:08
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/6d9a8754f59d7831ae9c to your computer and use it in GitHub Desktop.
Save komasaru/6d9a8754f59d7831ae9c to your computer and use it in GitHub Desktop.
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