how to test if a command line argument follows a certain regular expression

I would like to test if a command line argument follows a certain regular expression. if it does the boolean isSwitch turns to be true.

i tried it 2 different ways , for both of them i got errors.




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
  	vector<string>v;

	for (int i = 1; i < argc; ++i)
		v.push_back(argv[i]);


	regex switches("-(c|j|m|x|r|R|s|h|v)*");

	bool isSwitch = false;


	for (int unsigned i = 0; i < v.size(); ++i)
	{
		std::size_t found = v[i].find(switches);

		if (found != std::string::npos)
		{
			isSwitch = true;
		}


	}


	vector<string>::iterator p = find(v.begin(), v.end(), switches);
	if (p != v.end())
	{
		isSwitch = true;
		//v.erase(p);
	}
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
#include <iostream>
#include <string>
#include <regex>
#include <vector>
#include <iomanip>

int main( int argc, char* argv[] )
{
    // literal '-' followed by one of the alternatives repeated one or more times
    const std::regex options_re( "\\-(c|j|m|x|r|R|s|h|v)+" ) ;

    for( int i = 1 ; i < argc ; ++i )
    {
        std::cout << "argv[" << i << "] == " << std::quoted(argv[i]) << "  =>  " ;
        
        if( std::regex_match( argv[i], options_re ) ) std::cout << "matched\n" ;
        else std::cout << "not matched\n" ;
    }

    if( argc > 1 )
    {
        std::vector<std::string> args_vector( argv+1, argv+argc ) ;

        // ...
    }
}

http://coliru.stacked-crooked.com/a/d50882aa0885ea2c
Topic archived. No new replies allowed.