I'm learning regex for c++, and tried to make a simple function. It is very small but I'm satisfied, because this is the first time I managed to pass function as argument. This is a replace function. Please give me tips on how to improve:
std::string Replace(std::string text, std::regex reg, std::function<std::string(std::smatch)> func){
std::smatch matcher;
std::string result = "";
while (std::regex_search(text, matcher, reg))
{
result += matcher.prefix().str();
result += func(matcher);
text = matcher.suffix().str();
}
result += text;
return result;
}
Now here is a test, I pass a javascript like formatted string, with regex \\$\\{\\s*([a-zA-Z0-9]*?)\\s*\\} and I put my name and age into a variable.
int main(){
std::string name = "Ihsan";
std::string age = "13";
std::string text = "hello my name is ${name}, and im ${age} years old.";
std::regex pattern("\\$\\{\\s*([a-zA-Z0-9]*?)\\s*\\}");
std::cout << Replace(text, pattern, [name, age](auto matcher) -> std::string{
std::string str1 = matcher.str(1);
if(str1 == "name"){
return name;
}
if(str1 == "age"){
return age;
}
});
}
Output is:
hello my name is Ihsan, and im 13 years old.
[a-zA-Z0-9]*?: you don't need a non-greedy quantifier, use a greedy one[a-zA-Z0-9]*since the character class doesn't contain whitespaces nor closing curly bracket, your quantifier can blindly eat characters without to check the end of the pattern for each of them. \$\endgroup\$