Skip to content

Instantly share code, notes, and snippets.

@willkill07
Created December 7, 2016 21:21
Show Gist options
  • Save willkill07/61a4d0751d62a24bae4440c40576e736 to your computer and use it in GitHub Desktop.
Save willkill07/61a4d0751d62a24bae4440c40576e736 to your computer and use it in GitHub Desktop.
regular expression generator from pattern (e.g. abba)
#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;
}
@willkill07
Copy link
Author

willkill07 commented Dec 7, 2016

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:

./make_regex
abba
abba -> (.)(?!\1)(.)\2\1
abbbaaa
abbbaaa -> (.)(?!\1)(.)\2\2\1\1\1
abccba
abccba -> (.)(?!\1)(.)(?!\1|\2)(.)\3\2\1
abcdabcd
abcdabcd -> (.)(?!\1)(.)(?!\1|\2)(.)(?!\1|\2|\3)(.)\1\2\3\4
abcabcabc
abcabcabc -> (.)(?!\1)(.)(?!\1|\2)(.)\1\2\3\1\2\3
abbacca
abbacca -> (.)(?!\1)(.)\2\1(?!\1|\2)(.)\3\1
abbcccddddcccbba
abbcccddddcccbba -> (.)(?!\1)(.)\2(?!\1|\2)(.)\3\3(?!\1|\2|\3)(.)\4\4\4\3\3\3\2\2\1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment