使用Boost :: regex进行正则表达式组匹配

时间:2014-12-22 08:39:29

标签: c++ regex boost

我有格式的字符串:

7XXXX 8YYYY 9ZZZZ 0LLLL 7XXXX 8YYYY 9ZZZZ 0LLLL

  • 其中7XXXX 8YYYY 9ZZZZ 0LLLL个群组可以重复多次;
  • X,Y,Z,L是数字;
  • 以7,8,9,0开始的小组全部按顺序排列
  • 可能会缺少7XXXX 0LLLL 8YYYY 0LLLL 7XXXX 8YYYY 9ZZZZ 0LLLL
  • 等群组

我正在尝试使用Boost :: regex库来实现我的目标。

我想拆分这些组并将它们放入数组或向量中。现在我正试着cout他们。

我试图这样做,但我只能在7,8,9,0组的每个组中获得完整的字符串匹配或最后一个匹配,但不是像这些7XXXX 8YYYY 9ZZZZ 0LLLL

这样的字符串
 const char* pat = "(([[:space:]]+7[0-9]{4}){0,1}([[:space:]]+8[0-9]{4}){0,1}([[:space:]]+9[0-9]{4}){0,1}([[:space:]]+0[0-9]{4}){0,1})+";;
 boost::regex reg(pat);
 boost::smatch match;
 string example= "71122 85451 75415 01102 75555 82133 91341 02134";

 const int subgroups[] = {0,1,2,3,4,5,6};
 boost::sregex_token_iterator i(example.begin(), example.end(), reg, subgroups);
 boost::sregex_token_iterator j;

 while (i != j)
 {
   cout << "Match: " << *i++ << endl;
 }

示例输出:

Match: 71122 85451 75415 01102 75555 82133 91341 02134
<A bunch of empty "Match:" rows>
Match: 75555
Match: 82133
Match: 91341
Match: 02134
<A bunch of empty "Match:" rows>

但我希望得到这样的结果:

71122 85451 
75415 01102 
75555 82133 91341 02134

我知道我做错了,不能用正则表达式来做我想要的事情:(为什么我不能用括号获得所有的递归匹配?

2 个答案:

答案 0 :(得分:1)

编辑:由于我第一次完全误解了,我只会替换整个答案。我正在考虑这些问题:

const char* pat = "[[:space:]]+((7[0-9]{4})?([[:space:]]+8[0-9]{4})?([[:space:]]+9[0-9]{4})?([[:space:]]+0[0-9]{4})?)";
boost::regex reg(pat);
boost::smatch match;

//                    v-- extra space here to make the match easier.
std::string example= " 71122 85451 75415 01102 75555 82133 91341 02134";

boost::sregex_token_iterator i(example.begin(), example.end(), reg, 1);
boost::sregex_token_iterator j;

while (i != j)
{
  std::cout << "Match: " << *i++ << std::endl;
}

如果无法修改字符串,则解决空匹配问题的解决方法是

const char* pat = "((7[0-9]{4})?([[:space:]]+8[0-9]{4})?([[:space:]]+9[0-9]{4})?([[:space:]]+0[0-9]{4})?)";
boost::regex reg(pat);
boost::smatch match;
std::string example= "71122 85451 75415 01102 75555 82133 91341 02134";

boost::sregex_token_iterator i(example.begin(), example.end(), reg, 1);
boost::sregex_token_iterator j;

while (i != j)
{
  if(i->length() != 0) {
    std::cout << "Match: " << *i << std::endl;
  }

  ++i;
}

虽然在这种情况下使用regex_iterator代替regex_token_iterator可能更好:

// No need for outer spaces anymore
const char* pat = "(7[0-9]{4})?([[:space:]]+8[0-9]{4})?([[:space:]]+9[0-9]{4})?([[:space:]]+0[0-9]{4})?";

boost::sregex_iterator i(example.begin(), example.end(), reg);
boost::sregex_iterator j;

// Rest the same.

答案 1 :(得分:1)

我想我会在这里手动解析一个解析器。为了敏捷,如何用Spirit解析

  • 它直接解析为序列向量。
  • 处理空白没有问题。
  • 语法以syntax that somewhat resembles regular expressions but is tied in with the C++ language much stronger
  • 以声明方式描述
  • 它非常清楚地表达了意图:序列是预期顺序中任意项目的组合 - 只要结果至少有一个项目

    seq_  = -item_('7') >> -item_('8') >> -item_('9') >> -item_('0');
    

    其中item_解析以指示的数字开头的任何整数:

    item_  = &char_(_r1) >> uint_; 
    

    在解析器中,我们使用*seq解析任意数量的序列,这就是为什么我们添加了一个检查,即每个匹配的序列都不为空(否则我们可以获得在同一输入位置匹配空序列的无限循环)< / p>

    eps(phx::size(_val) > 0) // require 1 element at least
    
  • 请注意如何构建调试(通过取消注释第一行来启用它)。

  • 请注意,在Coliru上省略主角: See alternative version ,从结果中排除前导数字是多么微不足道:

    item_  = omit[char_(_r1)] >> uint_;
    

测试程序输出:

Parsing: 71122 85451 75415 01102 75555 82133 91341 02134
Parsed: 3 sequences

seq:    71122 85451 
seq:    75415 1102 
seq:    75555 82133 91341 2134

<强> Live On Coliru

//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace qi  = boost::spirit::qi;
namespace phx = boost::phoenix;

using data = std::vector<std::vector<unsigned> >;

template <typename It, typename Skipper = qi::space_type> 
struct grammar : qi::grammar<It, data(), Skipper> {
    grammar() : grammar::base_type(start) {
        using namespace qi;

        start = *seq_;

        seq_  = -item_('7') >> -item_('8') >> -item_('9') >> -item_('0')
              >> eps(phx::size(_val) > 0)
              ;

        item_ = &char_(_r1) >> uint_;

        BOOST_SPIRIT_DEBUG_NODES((start)(item_)(seq_))
    }

  private:
    qi::rule<It, unsigned(char), Skipper> item_;
    qi::rule<It, std::vector<unsigned>(), Skipper> seq_;
    qi::rule<It, data(), Skipper> start;
};

int main() { 

    for (std::string const input : {
            "71122 85451 75415 01102 75555 82133 91341 02134"
            })
    {
        using It = std::string::const_iterator;
        grammar<It> p;
        auto f(input.begin()), l(input.end());

        data parsed;
        bool ok = qi::phrase_parse(f,l,p,qi::space,parsed);

        std::cout << "Parsing: " << input << "\n";
        if (ok) {
            std::cout << "Parsed: " << parsed.size() << " sequences\n";
            for(auto& seq : parsed)
                std::copy(seq.begin(), seq.end(), std::ostream_iterator<unsigned>(std::cout << "\nseq:\t", " "));
            std::cout << "\n";
        } else {
            std::cout << "Parsed failed\n";
        }

        if (f!=l)
            std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
    }
}