0

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>();
4
  • 2
    And why are you not just finding GetPetDog and replace it with GetPet<Animal_Dog> ? Commented Jun 22, 2015 at 12:05
  • 1
    The search-replace mechanism in VS is pretty good, and can handle regular expressions. What have you tried so far? How did it fail? Commented Jun 22, 2015 at 12:07
  • The reason I don't want to use GetPetDog is because I've got over 20 pet types. I'm looking for something that can work generically for all the different types Commented Jun 22, 2015 at 12:14
  • I've tried a bunch of different ones, e.g. GetPet(.*), but that seems to be picking up the whole line. So if I have a call where it says e.g. GetPetDog().GiveFood(), it matches the whole line. So it replaces with GetPet<Animal_Dog().GiveFood()>(); I can't seem to get it to stop before the first bracket after Dog. Commented Jun 22, 2015 at 12:17

2 Answers 2

8

Use below regex:

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

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is exactly what I needed. Also, great link, I'll definitely use that in the future!
Accept the answer so that it may help to others also.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.