| 21 | } |
| 22 | |
| 23 | bool cmStringReplaceHelper::Replace(cm::string_view input, std::string& output) |
| 24 | { |
| 25 | output.clear(); |
| 26 | |
| 27 | unsigned optAnchor = 0; |
| 28 | if (this->Makefile && |
| 29 | this->Makefile->GetPolicyStatus(cmPolicies::CMP0186) != |
| 30 | cmPolicies::NEW) { |
| 31 | optAnchor = cmsys::RegularExpression::BOL_AT_OFFSET; |
| 32 | } |
| 33 | |
| 34 | // Scan through the input for all matches. |
| 35 | auto& re = this->RegularExpression; |
| 36 | std::string::size_type base = 0; |
| 37 | unsigned optNonEmpty = 0; |
| 38 | while (re.find(input.data(), base, optAnchor | optNonEmpty)) { |
| 39 | if (this->Makefile) { |
| 40 | this->Makefile->ClearMatches(); |
| 41 | this->Makefile->StoreMatches(re); |
| 42 | } |
| 43 | |
| 44 | // Concatenate the part of the input that was not matched. |
| 45 | output += input.substr(base, re.start() - base); |
| 46 | |
| 47 | // Concatenate the replacement for the match. |
| 48 | for (auto const& replacement : this->Replacements) { |
| 49 | if (replacement.Number < 0) { |
| 50 | // This is just a plain-text part of the replacement. |
| 51 | output += replacement.Value; |
| 52 | } else { |
| 53 | // Replace with part of the match. |
| 54 | auto n = replacement.Number; |
| 55 | if (n > re.num_groups()) { |
| 56 | std::ostringstream error; |
| 57 | error << "replace expression \"" << this->ReplaceExpression |
| 58 | << "\" contains an out-of-range escape for regex \"" |
| 59 | << this->RegExString << "\""; |
| 60 | this->ErrorString = error.str(); |
| 61 | return false; |
| 62 | } |
| 63 | output += re.match(n); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Move past the match. |
| 68 | base = re.end(); |
| 69 | |
| 70 | if (re.start() == input.length()) { |
| 71 | break; |
| 72 | } |
| 73 | if (re.start() == re.end()) { |
| 74 | optNonEmpty = cmsys::RegularExpression::NONEMPTY_AT_OFFSET; |
| 75 | } else { |
| 76 | optNonEmpty = 0; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // Concatenate the text after the last match. |