00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042 #include "pcre++.h"
00043
00044 using namespace std;
00045
00046
00047
00048
00049
00050 string Pcre::replace(const string& piece, const string& with) {
00051
00052
00053
00054 string Replaced(piece);
00055
00056 bool bReplaced = false;
00057 int iReplaced = -1;
00058
00059 __pcredebug << "replace: " << piece << " with: " << with << endl;
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071 pcre_free(p_pcre);
00072 pcre_free(p_pcre_extra);
00073
00074 pcre *_p = NULL;
00075 pcre_extra *_e = NULL;;
00076
00077 p_pcre = _p;
00078 p_pcre_extra = _e;
00079
00080 _expression = "(" + _expression + ")";
00081 Compile(_flags);
00082
00083 if(search(piece)) {
00084
00085
00086
00087
00088 string use_with;
00089
00090
00091 if(!global_t) {
00092
00093 use_with = _replace_vars(with);
00094
00095 if(matched() && matches() >= 1) {
00096 __pcredebug << "matches: " << matches() << endl;
00097 int len = get_match_end() - get_match_start() + 1;
00098 Replaced.replace(get_match_start(0), len, use_with);
00099 bReplaced = true;
00100 iReplaced = 0;
00101 }
00102 }
00103 else {
00104
00105
00106
00107
00108 int match_pos = 0;
00109 while( search( Replaced, match_pos ) ) {
00110 int len = 0;
00111
00112
00113
00114 use_with = _replace_vars(with);
00115
00116 len = get_match_end() - get_match_start() + 1;
00117 Replaced.replace(get_match_start(0), len, use_with);
00118
00119
00120 match_pos = ( use_with.length() - len ) + get_match_end() + 1;
00121
00122 bReplaced = true;
00123 ++iReplaced;
00124 }
00125 }
00126 }
00127
00128 did_match = bReplaced;
00129 num_matches = iReplaced;
00130
00131 return Replaced;
00132 }
00133
00134
00135
00136
00137
00138 string Pcre::_replace_vars(const string& piece) {
00139
00140
00141
00142 string with = piece;
00143 Pcre dollar("\\$([0-9]+)");
00144
00145 while ( dollar.search( with ) ) {
00146
00147 __pcredebug << "Pcre::dollar matched: " << piece << ". Match(0): " << dollar.get_match(0) << endl;
00148 int iBracketIndex = atoi( dollar.get_match(0).data() );
00149 string sBracketContent = get_match(iBracketIndex);
00150
00151
00152 string sSubSplit = "\\$" + dollar.get_match(0);
00153 Pcre subsplit(sSubSplit);
00154
00155
00156 Array splitted = subsplit.split(with);
00157 string Replaced;
00158
00159 for(size_t pos=0; pos < splitted.size(); pos++) {
00160 if( pos == ( splitted.size() - 1 ) )
00161 Replaced += splitted[pos];
00162 else
00163 Replaced += splitted[pos] + sBracketContent;
00164 }
00165 with = Replaced;
00166 }
00167 return with;
00168 }