【问题标题】:Is There a Way to Discard Empty Captures?有没有办法丢弃空捕获?
【发布时间】:2016-08-02 15:24:44
【问题描述】:

是否有一种内置方法可以仅迭代非空捕获,或者我是否需要使用 lambda/修改我的正则表达式?

例如,给定:const auto input = "Peas&Carrots Spinach-Casserole Beets Pizza Spinach-Salad Coleslaw"s 我想查找包含“菠菜”的食物。所以我可以这样做:

const regex re{ "\\s*(?:\\S*Spinach\\S*|(\\S*))" };

copy(sregex_token_iterator(cbegin(input), cend(input), re, 1), sregex_token_iterator(), ostream_iterator<string>(cout, "\n"));

问题当然是I get an output喜欢:

豌豆和胡萝卜

甜菜
比萨

凉拌卷心菜

有没有办法解决这个问题?

【问题讨论】:

    标签: c++ regex string iterator spinach


    【解决方案1】:

    您可以使用std::copy_if 和 lambda 来检查正则表达式匹配中的字符串是否为空。使用

    copy_if(sregex_token_iterator(cbegin(input), cend(input), re, 1), 
            sregex_token_iterator(), ostream_iterator<string>(cout, "\n"), 
            [](const std::string& match){ return !match.empty(); });
    

    我们得到

    Peas&Carrots
    Beets
    Pizza
    Coleslaw
    

    Live Example

    因为它只会打印非空字符串。

    【讨论】:

      【解决方案2】:

      显而易见的方法是使用std::copy_if(或std::remove_copy_if)并仅在字符串非空时复制该字符串。

      remove_copy_if(
          sregex_token_iterator(cbegin(input), cend(input), re, 1),  
          sregex_token_iterator(), 
          ostream_iterator<string>(cout, "\n"),
          [](string const &s) { return s.empty(); } 
      );
      

      【讨论】:

        【解决方案3】:

        从那些比我聪明的人的答案看来,实际上没有 lambda 就没有办法丢弃空结果。在这个问题中,有几个选择:

        1. 使用 Look Ahead,这有点贵,但只能捕获没有“Spinach”的单词:
        const regex re{ "(?:\\s+|^)(?!Spinach)(\\S+)" };
        
        copy(sregex_token_iterator(cbegin(input), cend(input), re, 1), sregex_token_iterator(), ostream_iterator<string>(cout, "\n"));
        

        Live Example

        1. 使用 istream_iterator 和 lambda,这会大大降低 lambda 的灵活性,但由于 input 是用空格分隔的,这可能是最好的选择:​​i>
        istringstream{ input };
        
        copy_if(istream_iterator<string>(cbegin(input), cend(input)), istream_iterator<string>(), ostream_iterator<string>(cout, "\n"), [](const auto& i) { return i.find("Spinach") == string::npos; });
        

        Live Example

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-17
          • 2019-12-26
          • 1970-01-01
          • 1970-01-01
          • 2011-08-31
          • 1970-01-01
          • 1970-01-01
          • 2010-11-24
          相关资源
          最近更新 更多