Pre-Compiled Regular Expressions
To use RANS is pretty easy. first of all, you should compile it once to an RANS object and reuse that object for each call.
Example:
RANS rans("[ab]*[ac][abc]{3}");
assert(rans.ok); // compiled; if not, see rans.error();
Encoding Interface
There are two fundamental functions: RANS::val requires string that can be matched against a regular expression, and RANS::rep, which is inverse function of RANS::val, looks for a corressponding string by given value. These functions are wrapped RANS::operator()
Example:
RANS rans("a*(b*|c*)");
assert(rans("aaa")==9); // rans.rep("aaa")
assert(rans(9)=="aaa"); // rans.val(9)
assert(rans("")==0); // rans.rep("")
The return value of RANS::val and argument of RANS::rep is RANS::Value. that is wrapper type of mpz_class (in gmpxx.h)
RANS rans("a*(b*|c*)");
RANS::Value value; std::string text = "aaa";
assert(rans(text, value)==9); // set value to 9, and return reference
assert(rans(value, text)=="aaa"); // set text to "aaa", and return reference
Exception
An RANS::Exception will be thrown If you give a bad (not acceptable) string (or value) to RANS::val. Therefore, You should assure that string is acceptable when calling RANS::rep. you can verify whether string is acceptable via RANS::accept method just like:
RANS rans("a*(b*|c*)");
if(rans.accept(text)) val(text, value);
RANS only_accept_a("a");
only_accept_a("b"); // raise exception!
Sample Code
Here is the code of the simple but complete encode & decode REPL program.
// repl.cc
#include <rans.hpp>
#include <iostream>
int main() {
std::string regex;
std::cout << "regex: ";
std::cin >> regex;
RANS rans(regex);
if(!rans.ok()) {
std::cout << rans.error() << std::endl;
exit(0);
}
RANS::Value value;
std::string text;
while (std::cout << "text: " && std::cin >> text) {
try {
std::cout << "val(text): " << rans(text, value) << std::endl;
std::cout << "rep(value): " << rans(value, text) << std::endl;
} catch (const RANS::Exception& e) {
std::cout << e.what() << std::endl;
}
}
return 0;
}
You could compile this like as:
$ g++ repl.cc -lgmp -lgmpxx -o repl
$ ./repl
Additional Tips and Tricks
For advanced usage, like compression, or something that uses a DFA directly, see rans.hpp or codes in test directory.
Back to main page