Added caching for regular expression + conditional encoding + small refactoring