00001 00014 #ifndef OP_REGEX_H 00015 #define OP_REGEX_H 00016 00017 // required by posix before including regex.h 00018 #include <sys/types.h> 00019 #include <regex.h> 00020 00021 #include <string> 00022 #include <vector> 00023 #include <map> 00024 00025 #include "op_exception.h" 00026 00030 struct bad_regex : op_exception { 00031 bad_regex(std::string const & pattern); 00032 }; 00033 00039 class regular_expression_replace { 00040 public: 00049 regular_expression_replace(size_t limit = 100, 00050 size_t limit_defs_expansion = 100); 00051 ~regular_expression_replace(); 00052 00059 void add_definition(std::string const & name, 00060 std::string const & replace); 00068 void add_pattern(std::string const & pattern, 00069 std::string const & replace); 00070 00083 bool execute(std::string & str) const; 00084 private: 00085 struct replace_t { 00086 // when this regexp is matched 00087 regex_t regexp; 00088 // replace the matched part with this string 00089 std::string replace; 00090 }; 00091 00092 // helper to execute 00093 bool do_execute(std::string & str, replace_t const & regexp) const; 00094 void do_replace(std::string & str, std::string const & replace, 00095 regmatch_t const * match) const; 00096 00097 // helper to add_definition() and add_pattern() 00098 std::string expand_string(std::string const & input); 00099 00100 // helper to add_pattern 00101 std::string substitute_definition(std::string const & pattern); 00102 00103 // return the match of throw if idx is invalid 00104 regmatch_t const & get_match(regmatch_t const * match, char idx) const; 00105 00106 // don't increase too, it have direct impact on performance. This limit 00107 // the number of grouping expression allowed in a regular expression 00108 // Note than you can use grouping match operator > 9 only in the 00109 // replace rule not in match regular expression since POSIX don't allow 00110 // more than \9 in matching sequence. 00111 static const size_t max_match = 16; 00112 00113 size_t limit; 00114 size_t limit_defs_expansion; 00115 std::vector<replace_t> regex_replace; 00117 typedef std::map<std::string, std::string> defs_dict; 00118 defs_dict defs; 00119 }; 00120 00127 void setup_regex(regular_expression_replace& regex, 00128 std::string const & filename); 00129 00130 #endif /* !OP_REGEX_H */