Retrieve everything except what is indicated in the regular expression

I have the following code:

#include <iostream> #include <regex> using namespace std; int main() { string s; s = "server ('m1.labs.terad ''ata.com') username ('us\* er5') password('user)5') dbname ('def\\ault')"; regex re("('[^']*(?:''[^']*)*')"); // I have used -1 to extract everything apart from the content there in brackets. sregex_token_iterator i(s.begin(), s.end(), re, -1); sregex_token_iterator j; unsigned count = 0; while(i != j) { cout <<*i<< endl; count++; i++; } cout << "There were " << count << " tokens found." << endl; return 0; } 

The regex above is for retrieving an argument name such as server, username, password, etc.

But this is the result that I get:

 server ( ) username ( ) password( ) dbname ( ) There were 5 tokens found. 

But the expected result:

 server username password dbname There were 4 tokens found. 

Please help me where I am missing. thanks in advance

0
source share
1 answer

From the <strike> spite of pity, here is a solution based on the previous answer:
extract string with single quotes between brackets and single quote

Change main to:

 int main() { auto const text = "server ('m1.labs.terad ''ata.com') username ('us\\* er5') password('user)5') dbname ('def\\ault')"; Config cfg = parse_config(text); for (auto& setting : cfg) //std::cout << "Key " << setting.first << " has value " << setting.second << "\n"; std::cout << setting.first << "\n"; } 

Print

 dbname password server username 

Live on coliru

 #include <iostream> #include <boost/spirit/home/x3.hpp> #include <boost/fusion/adapted/std_pair.hpp> #include <map> using Config = std::map<std::string, std::string>; using Entry = std::pair<std::string, std::string>; namespace parser { using namespace boost::spirit::x3; namespace { template <typename T> struct as_type { template <typename Expr> auto operator[](Expr expr) const { return rule<struct _, T>{"as"} = expr; } }; template <typename T> static const as_type<T> as = {}; } auto quoted = [](char q) { return lexeme[q >> *(q >> char_(q) | '\\' >> char_ | char_ - q) >> q]; }; auto value = quoted('\'') | quoted('"'); auto key = lexeme[+alpha]; auto pair = key >> '(' >> value >> ')'; auto config = skip(space) [ *as<Entry>[pair] ]; } Config parse_config(std::string const& cfg) { Config parsed; auto f = cfg.begin(), l = cfg.end(); if (!parse(f, l, parser::config, parsed)) throw std::invalid_argument("Parse failed at " + std::string(f,l)); return parsed; } int main() { auto const text = "server ('m1.labs.terad ''ata.com') username ('us\\* er5') password('user)5') dbname ('def\\ault')"; Config cfg = parse_config(text); for (auto& setting : cfg) //std::cout << "Key " << setting.first << " has value " << setting.second << "\n"; std::cout << setting.first << "\n"; } 

Print

 dbname password server username 
0
source

Source: https://habr.com/ru/post/1270131/


All Articles