* @brief PCRE compiles the regex, called only during initialization. * @return true if successful, false if not. */
| 323 | * @return true if successful, false if not. |
| 324 | */ |
| 325 | bool |
| 326 | Pattern::compile() |
| 327 | { |
| 328 | const char *errPtr; /* PCRE error */ |
| 329 | int errOffset; /* PCRE error offset */ |
| 330 | |
| 331 | PrefetchDebug("compiling pattern:'%s', replacement:'%s'", _pattern.c_str(), _replacement.c_str()); |
| 332 | |
| 333 | _re = pcre_compile(_pattern.c_str(), /* the pattern */ |
| 334 | 0, /* options */ |
| 335 | &errPtr, /* for error message */ |
| 336 | &errOffset, /* for error offset */ |
| 337 | nullptr); /* use default character tables */ |
| 338 | |
| 339 | if (nullptr == _re) { |
| 340 | PrefetchError("compile of regex '%s' at char %d: %s", _pattern.c_str(), errOffset, errPtr); |
| 341 | |
| 342 | return false; |
| 343 | } |
| 344 | |
| 345 | _extra = pcre_study(_re, 0, &errPtr); |
| 346 | |
| 347 | if ((nullptr == _extra) && (nullptr != errPtr) && (0 != *errPtr)) { |
| 348 | PrefetchError("failed to study regex '%s': %s", _pattern.c_str(), errPtr); |
| 349 | |
| 350 | pcre_free(_re); |
| 351 | _re = nullptr; |
| 352 | return false; |
| 353 | } |
| 354 | |
| 355 | if (_replacement.empty()) { |
| 356 | /* No replacement necessary - we are done. */ |
| 357 | return true; |
| 358 | } |
| 359 | |
| 360 | _tokenCount = 0; |
| 361 | bool success = true; |
| 362 | |
| 363 | for (unsigned i = 0; i < _replacement.length(); i++) { |
| 364 | if (_replacement[i] == '$') { |
| 365 | if (_tokenCount >= TOKENCOUNT) { |
| 366 | PrefetchError("too many tokens in replacement string: %s", _replacement.c_str()); |
| 367 | |
| 368 | success = false; |
| 369 | break; |
| 370 | } else if (_replacement[i + 1] < '0' || _replacement[i + 1] > '9') { |
| 371 | PrefetchError("invalid replacement token $%c in %s: should be $0 - $9", _replacement[i + 1], _replacement.c_str()); |
| 372 | |
| 373 | success = false; |
| 374 | break; |
| 375 | } else { |
| 376 | /* Store the location of the replacement */ |
| 377 | /* Convert '0' to 0 */ |
| 378 | _tokens[_tokenCount] = _replacement[i + 1] - '0'; |
| 379 | _tokenOffset[_tokenCount] = i; |
| 380 | _tokenCount++; |
| 381 | /* Skip the next char */ |
| 382 | i++; |