Match string exactly with regex

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))) );

So the question is how do I define str_pattern?

1
2
3
4
std::string str_pattern(const std::string& str)
{
	return ???
}
Last edited on
Do you mean something ike this?

1
2
3
4
5
6
7
8
9
10
11
12
13
// Assuming ERE grammar
std::string str_pattern(const std::string& str)
{
    static const std::string special {"^.[$()|*+?{\\"};
    std::string s = "^";
    for (char c: str)
    {
        if (special.find(c) != special.npos)
            s += "\\";
        s += c;
    }
    return s + "$";
}

Last edited on
Yes, that seems to be exactly what I want. Thank you.

Is "ERE grammar" what std::regex use by default ?
Last edited on
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:

 
    static const std::string special {"^.[]$()|*+?{}\\"};

OK, thanks. :)
why are you doing this instead of string == string ? (curious only, as it seems regex is much more overhead for this check)
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.
Last edited on
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.
Topic archived. No new replies allowed.