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 using namespace pcrepp;
00046
00047
00048
00049
00050
00051 string Pcre::replace(const string& piece, const string& with) {
00052
00053
00054
00055 string Replaced(piece);
00056
00057 bool bReplaced = false;
00058 int iReplaced = -1;
00059
00060 __pcredebug << "replace: " << piece << " with: " << with << endl;
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072 pcre_free(p_pcre);
00073 pcre_free(p_pcre_extra);
00074
00075 pcre *_p = NULL;
00076 pcre_extra *_e = NULL;;
00077
00078 p_pcre = _p;
00079 p_pcre_extra = _e;
00080
00081 if ( _expression[0] != '(' )
00082 _expression = "(" + _expression;
00083
00084 if ( _expression[_expression.size()-1] != ')' )
00085 _expression=_expression + ")";
00086
00087 Compile(_flags);
00088
00089 if(search(piece)) {
00090
00091
00092
00093
00094 string use_with;
00095
00096
00097 if(!global_t) {
00098
00099 use_with = _replace_vars(with);
00100
00101 if(matched() && matches() >= 1) {
00102 __pcredebug << "matches: " << matches() << endl;
00103 int len = get_match_end() - get_match_start() + 1;
00104 Replaced.replace(get_match_start(0), len, use_with);
00105 bReplaced = true;
00106 iReplaced = 0;
00107 }
00108 }
00109 else {
00110
00111
00112
00113
00114 int match_pos = 0;
00115 while( search( Replaced, match_pos ) ) {
00116 int len = 0;
00117
00118
00119
00120 use_with = _replace_vars(with);
00121
00122 len = get_match_end() - get_match_start() + 1;
00123 Replaced.replace(get_match_start(0), len, use_with);
00124
00125
00126 match_pos = ( use_with.length() - len ) + get_match_end() + 1;
00127
00128 bReplaced = true;
00129 ++iReplaced;
00130 }
00131 }
00132 }
00133
00134 did_match = bReplaced;
00135 num_matches = iReplaced;
00136
00137 return Replaced;
00138 }
00139
00140
00141
00142
00143
00144 string Pcre::_replace_vars(const string& piece) {
00145
00146
00147
00148 string with = piece;
00149 Pcre dollar("\\$([0-9]+)");
00150
00151 while ( dollar.search( with ) ) {
00152
00153 __pcredebug << "Pcre::dollar matched: " << piece << ". Match(0): " << dollar.get_match(0) << endl;
00154 int iBracketIndex = atoi( dollar.get_match(0).data() );
00155 string sBracketContent = get_match(iBracketIndex);
00156
00157
00158 string sSubSplit = "\\$" + dollar.get_match(0);
00159 Pcre subsplit(sSubSplit);
00160
00161
00162 vector<string> splitted = subsplit.split(with);
00163 string Replaced;
00164
00165 for(size_t pos=0; pos < splitted.size(); pos++) {
00166 if( pos == ( splitted.size() - 1 ) )
00167 Replaced += splitted[pos];
00168 else
00169 Replaced += splitted[pos] + sBracketContent;
00170 }
00171 with = Replaced;
00172 }
00173 return with;
00174 }