Home > Enterprise >  Regex match all except first instance
Regex match all except first instance

Time:10-11

I am struggling to find a working regex pattern to match all instances of a string except the first.

I am using std::regex_replace to add a new line before each instance of a substring with a new line. however none of the googling I have found so far has produced a working regex pattern for this.

outputString = std::regex_replace(outputString, std::regex("// ~"), "\n// ~");

So all but the first instance of // ~ should be changed to \n// ~

CodePudding user response:

In this case, I'd advise being the anti-Nike: "Just don't do it!"

The pattern you're searching for is trivial. So is the replacement. There's simply no need to use a regex at all. Under the circumstances, I'd just use std::string::find in a loop, skipping replacement of the first instance you find.

std::string s = "a = b; // ~ first line // ~ second line // ~ third line";

std::string pat = "// ~";
std::string rep = "\n// ~";

auto pos = s.find(pat); // first one, which we skip
while ((pos=s.find(pat, pos pat.size())) != std::string::npos) {
    s.replace(pos, pat.size(), rep);
    pos  = rep.size() - pat.size();
}
std::cout << s << "\n";

When you're doing a replacement like this one, where the replacement string includes a copy of the string you're searching for, you have to be a little careful about where you start second (and subsequent) searches, to assure that you don't repeatedly find the same string you just replaced. That's why we keep track of the current position, and each subsequent search we make, we move the starting point far enough along that we won't find the same instance of the pattern again and again.

  • Related