I want to create a std::regex that matches a std::string exactly. I have tried by just passing the string as argument to the regex constructor but that will obviously not work if the string contains special characters such as +.
1 2
// I want this assert to pass for any value of str1 and str2.
assert( (str1 == str2) == std::regex_match(str1, std::regex(str_pattern(str2))) );
// Assuming ERE grammar
std::string str_pattern(const std::string& str)
{
staticconst std::string special {"^.[$()|*+?{\\"};
std::string s = "^";
for (char c: str)
{
if (special.find(c) != special.npos)
s += "\\";
s += c;
}
return s + "$";
}
Actually, it seems that the default is the ECMAScript (basically JavaScript) regex grammar.
But the special characters are the same as ERE (extended regex).
You might want to add the closing square and curly braces, though:
staticconst std::string special {"^.[]$()|*+?{}\\"};
The user can specify a name and optionally a pattern, among other things. If the pattern is left out I want to set the pattern so that it matches the name. I'm aware that this might not be the most efficient solution but performance is not extremely important for what I'm doing and treating everything the same just makes the code simpler.
Makes perfect sense. Could be it is the best, too... this kind of code, detecting a special case that can reduce work done often costs as much or more than just doing it the harder way without the detection.