How to parse a command line with regular expressions?

后端 未结 13 677
离开以前
离开以前 2020-12-03 16:02

I want to split a command line like string in single string parameters. How look the regular expression for it. The problem are that the parameters can be quoted. For exampl

13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 16:20

    ("[^"]+"|[^\s"]+)
    

    what i use C++

    #include 
    #include 
    #include 
    #include 
    
    void foo()
    {
        std::string strArg = " \"par   1\"  par2 par3 \"par 4\""; 
    
        std::regex word_regex( "(\"[^\"]+\"|[^\\s\"]+)" );
        auto words_begin = 
            std::sregex_iterator(strArg.begin(), strArg.end(), word_regex);
        auto words_end = std::sregex_iterator();
        for (std::sregex_iterator i = words_begin; i != words_end; ++i)
        {
            std::smatch match = *i;
            std::string match_str = match.str();
            std::cout << match_str << '\n';
        }
    }
    

    Output:

    "par   1"
    par2
    par3
    "par 4"
    

提交回复
热议问题