Using the new C++11 regular expressions, command line option parsing becomes trivial. I wrote a lightweight command line options parser because I was unsatisfied with all of the other libraries out there. They either do not support the syntax that I like, or they are bloated, trying to do too much.
There are two pieces of syntax that need to be parsed in specifying command line options:
- the specification of which options to recognise, and
- the command line options themselves.
To recognise these, we have two regular expressions. For the first, we want to be able to write something like
"f,file", to specify a short and long option, where either are optional. For the second, we want to recognise long options, with or without
=, and short options that can be grouped together, with the last option being able to take a parameter.
The two regular expressions are:
std::basic_regex<char> option_matcher ("--([[:alpha:]][-_[:alpha:]]+)(=(.*))?|-([[:alpha:]]+)"); std::basic_regex<char> option_specifier ("(([[:alpha:]]),)?([[:alpha:]][-_[:alpha:]]+)");
Then the rest of the code is there to loop through the options, ask the regex to match them, and store them somewhere.
The library can be found at http://github.com/jarro2783/cxxopts.
From → Uncategorized