user3163192
user3163192

Reputation: 111

Find and replace with regular expressions

I'm trying to replace a bunch of function calls using regular expressions but can't seem to be getting it right. This is a simplified example of what I'm trying to do:

GetPetDog();
GetPetCat();
GetPetBird();

I want to change to:

GetPet<Animal_Dog>();
GetPet<Animal_Cat>();
GetPet<Animal_Bird>();

Upvotes: 0

Views: 87

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626923

You can use the following regex and code for that:

std::string ss ("GetPetDog();");
static const std::regex ee ("GetPet([^()]*)");
std::string result;
result = regex_replace(ss, ee, "GetPet<Animal_$1>");
std::cout << result << endl;

Regex:

  • GetPet - Matches GetPet literally (we need no capturing group here)
  • ([^()]*) - A capturing group to match any characters other than ( or ) 0 or more times (*)

Output:

enter image description here

Upvotes: 0

Rahul
Rahul

Reputation: 3509

Use below regex:

(GetPet)([^(]*) with subsitution \1<Animal_\2>

Demo

Upvotes: 8

Related Questions