* @brief Replaces all replacements found in the replacement string with what matched in the PCRE capturing groups. * @param subject PCRE subject string * @param result reference to A string where the result of the replacement will be stored * @return true - success, false - nothing matched or failure. */
| 267 | * @return true - success, false - nothing matched or failure. |
| 268 | */ |
| 269 | bool |
| 270 | Pattern::replace(const String &subject, String &result) |
| 271 | { |
| 272 | int matchCount; |
| 273 | int ovector[OVECOUNT]; |
| 274 | |
| 275 | PrefetchDebug("matching '%s' to '%s'", _pattern.c_str(), subject.c_str()); |
| 276 | |
| 277 | if (!_re) { |
| 278 | return false; |
| 279 | } |
| 280 | |
| 281 | matchCount = pcre_exec(_re, nullptr, subject.c_str(), subject.length(), 0, PCRE_NOTEMPTY, ovector, OVECOUNT); |
| 282 | if (matchCount < 0) { |
| 283 | if (matchCount != PCRE_ERROR_NOMATCH) { |
| 284 | PrefetchError("matching error %d", matchCount); |
| 285 | } |
| 286 | return false; |
| 287 | } |
| 288 | |
| 289 | /* Verify the replacement has the right number of matching groups */ |
| 290 | for (int i = 0; i < _tokenCount; i++) { |
| 291 | if (_tokens[i] >= matchCount) { |
| 292 | PrefetchError("invalid reference in replacement string: $%d", _tokens[i]); |
| 293 | return false; |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | int previous = 0; |
| 298 | for (int i = 0; i < _tokenCount; i++) { |
| 299 | int replIndex = _tokens[i]; |
| 300 | int start = ovector[2 * replIndex]; |
| 301 | int length = ovector[2 * replIndex + 1] - ovector[2 * replIndex]; |
| 302 | |
| 303 | String src(_replacement, _tokenOffset[i], 2); |
| 304 | String dst(subject, start, length); |
| 305 | |
| 306 | PrefetchDebug("replacing '%s' with '%s'", src.c_str(), dst.c_str()); |
| 307 | |
| 308 | result.append(_replacement, previous, _tokenOffset[i] - previous); |
| 309 | result.append(dst); |
| 310 | |
| 311 | previous = _tokenOffset[i] + 2; /* 2 is the size of $0 or $1 or $2, ... or $9 */ |
| 312 | } |
| 313 | |
| 314 | result.append(_replacement, previous, _replacement.length() - previous); |
| 315 | |
| 316 | PrefetchDebug("replacing '%s' resulted in '%s'", _replacement.c_str(), result.c_str()); |
| 317 | |
| 318 | return true; |
| 319 | } |
| 320 | |
| 321 | /** |
| 322 | * @brief PCRE compiles the regex, called only during initialization. |
no test coverage detected