Reputation: 19893
I've got the following string :
const std::string args = "cmdLine=\"-d ..\\data\\configFile.cfg\" rootDir=\"C:\\abc\\def\""; // please note the space after -d
I'd like to split it into 2 substrings :
std::str1 = "cmdLine=...";
and
std::str2 = "rootDir=...";
using boost/algorithm/string.hpp . I figured, regular expressions would be best for this but unfortunately I have no idea how to construct one therefore I needed to ask the question.
Anyone capable of helping me out with this one?
Upvotes: 0
Views: 195
Reputation: 99585
To solve problem from your question the easiest way is to use strstr to find substring in string, and string::substr to copy substring. But if you really want to use Boost and regular expressions you could make it as in the following sample:
#include <boost/regex.hpp>
...
const std::string args = "cmdLine=\"-d ..\\data\\configFile.cfg\" rootDir=\"C:\\abc\\def\"";
boost::regex exrp( "(cmdLine=.*) (rootDir=.*)" );
boost::match_results<string::const_iterator> what;
if( regex_search( args, what, exrp ) ) {
string str1( what[1].first, what[1].second ); // cmdLine="-d ..\data\configFile.cfg"
string str2( what[2].first, what[2].second ); // rootDir="C:\abc\def"
}
Upvotes: 1
Reputation: 1727
Code samples
char *cstr1 = (char*)args.c_str();
char *cstr2 = strstr(cstr1, "=\""); cstr2 = strstr(cstr2, "=\"); // rootDir="
cstr2 = strrchr(cstr2, ' '); // space between " and rootDir
*cstr2++ = '\0';
//then save to your strings
std::string str1 = cstr1;
std::string str2 = cstr2;
that's all.
Notes: Above code supports these strings
"cmdLine=\"-d ..\\data\\configFile.cfg\" rootDir=\"C:\\abc\\def\"" or
"ABCwhatever=\"-d ..\\data\\configFile.cfg\" XYZ=\"C:\\abc\\def\""
Upvotes: 1