Regex matching quoted strings
Hello all, I got Regex to compile and link into a project using MSVC6. My problem is in trying to implementing a command line parsing regexp that handles quoted strings. I have code that will selectively match quoted strings but somehow ignores non-quoted strings. The code fragment is below. I've read over Mastering Regular Expressions and some Perl Cookbook stuff but nothing works straight out of the book. Any tips? The code below finds all three parameters (in the spec var), but has no match for 'parm1'. Any help is certainly appreciated. Thanks. ----- 8< ----- 8< ----- boost::regex exp( "\"(?:(\\\\.|[^\"])*)\"[:space:]*" "|" "([^[:space:]]+)[:space:]*" ); std::string str = "parm1 \"parm2 parm3\" \"parm4 \\\"yo\\\"\""; std::string::const_iterator start = str.begin(), end = str.end(); boost::match_resultsstd::string::const_iterator what; unsigned int flags = boost::match_default; while (boost::regex_search(start, end, what, exp, flags)) { std::string spec(what[0].first, what[0].second-what[0].first); std::string match(what[1].first, what[1].second-what[1].first); start = what[0].second; } ----- 8< ----- 8< ----- --- Shawn Poulson
Any help is certainly appreciated. Thanks.
Remember that if the expression matches a non-quoted string then the bit you want is actually in $2 not $1, here's what I came up with: boost::regex exp( "\"((?:[^\\\\\"]|\\\\.)+)\"[:space:]*" "|" "([^[:space:]]+)[:space:]*" ); std::string str = "parm1 \"parm2 parm3\" \"parm4 \\\"yo\\\"\""; std::string::const_iterator start = str.begin(), end = str.end(); boost::match_resultsstd::string::const_iterator what; unsigned int flags = boost::match_default; while (boost::regex_search(start, end, what, exp, flags)) { std::string spec(what[0]); std::string match; if(what[1].matched) match = what[1]; // quoted string else match = what[2]; // non-quoted string start = what[0].second; std::cout << spec << std::endl; std::cout << match << std::endl << std::endl; } which prints: parm1 parm1 "parm2 parm3" parm2 parm3 "parm4 \"yo\"" parm4 \"yo\" which looks like what you want? John Maddock http://ourworld.compuserve.com/homepages/john_maddock/index.htm
participants (2)
-
John Maddock
-
Poulson, Shawn