A templatized regex match function

I am trying to code a parameterized regex match() function.

The idea is to create a function which can accept any regex as a template parameter and return the matches.

My first version is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/// function template match<> to match a string
/// with a parameterized regex.

#include <regex>
#include <iostream>

using namespace std;

vector<string> lines {"TX77845", "TX 77504", "Hello"};

/// US ZIP code pattern: XXddddd-dddd and variants
regex USZipCode {R"(\w{2}\s*\d{5}(-\d{4})?)"};


template<typename R>
void rmatch(string s)
{
    /// matched strings go here
    smatch matches;

    if (regex_match(s, matches, R))		/// line 27: 1st error here
        cout << "match : " << matches[0] << '\n';
    else
        cout << "no match\n";

    cout << endl;
}


int main()
{
    for (auto l : lines)
    {
        /// matched strings go here
        smatch matches;

        rmatch<USZipCode>(l);			/// line 43: 2nd error here
    }
}


http://cpp.sh/7x4jg

However, it gives a compilation error:


In function 'void rmatch(std::string)':
27:34: error: expected primary-expression before ')' token

 In function 'int main()':
43:28: error: no matching function for call to 'rmatch(std::basic_string<char>&)'
43:28: note: candidate is:

22:6: note: template<class R> void rmatch(std::string)
22:6: note:   template argument deduction/substitution failed:


I'm unable to figure out the reason for these errors. Why is this happening?

Thanks.
Last edited on
The template parameter R expects a type but you try to pass it a variable. You'll have to pass the regex as a regular argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <regex>
#include <iostream>

using namespace std;

vector<string> lines {"TX77845", "TX 77504", "Hello"};

/// US ZIP code pattern: XXddddd-dddd and variants
regex USZipCode {R"(\w{2}\s*\d{5}(-\d{4})?)"};


template<typename R>
void rmatch(string s, R r)
{
    /// matched strings go here
    smatch matches;

    if (regex_match(s, matches, r))
        cout << "match : " << matches[0] << '\n';
    else
        cout << "no match\n";

    cout << endl;
}


int main()
{
    for (auto l : lines)
    {
        /// matched strings go here
        smatch matches;

        rmatch(l, USZipCode);
    }
}
Last edited on
You probably mean:
 
if (regex_match(s, matches, USZipCode))
Topic archived. No new replies allowed.