Created
December 7, 2016 21:21
-
-
Save willkill07/61a4d0751d62a24bae4440c40576e736 to your computer and use it in GitHub Desktop.
regular expression generator from pattern (e.g. abba)
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 <iostream> | |
#include <map> | |
#include <sstream> | |
#include <string> | |
std::string from_pattern(std::string pattern) { | |
int i{0}; | |
std::map<char, int> m; | |
std::ostringstream s; | |
for (char c : pattern) { | |
auto t = m.find(c); | |
if (t != m.end()) { | |
s << '\\' << t->second; | |
continue; | |
} | |
t = m.begin(); | |
if (t != m.end()) { | |
s << "(?!\\" << t->second; | |
while (++t != m.end()) | |
s << "|\\" << t->second; | |
s << ")"; | |
} | |
s << "(.)"; | |
m.emplace(c, ++i); | |
} | |
return s.str(); | |
} | |
int main() { | |
std::string line; | |
while (std::getline(std::cin, line)) | |
std::cout << line << " -> " << from_pattern(line) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile:
If you have a c++11 compliant compiler and make installed:
CXXFLAGS='-std=c++11' make make_regex
If you have no idea, try:
g++ -std=c++11 make_regex.cpp -o make_regex
Run: