提取除正则表达式

时间:2017-07-24 07:34:37

标签: c++ regex string

我有以下代码:

#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;
}

上面的正则表达式旨在提取参数名称,例如服务器,用户名,密码等。

但这是我得到的输出:

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

但我期待的输出是:

server
username
password
dbname
There were 4 tokens found.

请在我错过的地方帮助我。提前致谢

1 个答案:

答案 0 :(得分:0)

出于 spite 可惜,这是基于前一个答案的解决方案:
extract a string with single quotes between parenthesis and single quote

main更改为:

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";
}

打印

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";
}

打印

dbname
password
server
username