使用c ++正则表达式并且结果太慢

时间:2016-02-22 06:04:59

标签: c++ regex

速度对我来说是非常重要的标准。这是我的字符串

let size:[String: [Size: String]] = [
    String(Lumber): lumberSize,
    String(Fruit): fruitSize
]

我想获取每个块名称和内部内容,我正在使用c ++正则表达式,这是我的正则表达式和正则表达式搜索代码

DataInfoBlock1 {

    Some description
}

DataInfoBlock2 {

    Some other informations
}

Block3 {

    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
    Anything = vl;
}

我的结果是

smatch Matches;
string Rgx("[[:blank:]]*([^]*?)[[:blank:]]*[{][[:blank:]]*([^]*?)[[:blank:]]*[}]", regex::optimize);

while(regex_search(str, Matches, Rgx))
{

}

我得到了完整的matche,块名和内部数据,但速度非常非常糟糕(需要大约一秒钟)才能获得匹配!我该怎么做才能更快地获得结果?是这个正则表达式优化?我必须使用什么正则表达式来获得这样的结果,但是在非常快的时间?

1 个答案:

答案 0 :(得分:0)

也许试试这个:

#include <regex>
#include <iostream>

const std::string s = R"~(
DataInfoBlock1 {

    Some description
}

DataInfoBlock2 {

    Some other informations
}

Block3 {

    Anything = vl;
    Anything = vl;
}
)~";

int main()
{    
    std::regex e(R"~((\w+)\s+\{([^}]+)\})~", std::regex::optimize);

    std::sregex_iterator iter(s.begin(), s.end(), e);
    std::sregex_iterator end;

    for(; iter != end; ++iter)
    {
        std::cout << "-----------------------------" << '\n';
        std::cout << "name: " << iter->str(1) << '\n';
        std::cout << "contents: " << iter->str(2) << '\n';
    }
}

<强>输出:

-----------------------------
name: DataInfoBlock1
contents: 

    Some description

-----------------------------
name: DataInfoBlock2
contents: 

    Some other informations

-----------------------------
name: Block3
contents: 

    Anything = vl;
    Anything = vl;

Tested Here