2012-11-01 16 views
3

如何獲取boost :: regex (basic_regex<char, regex_traits<char> >)對象中的子表達式。 (無文字compare- befroe做boost::regex_search從boost :: regex(匹配前)獲取子表達式

例子:

表達: XX * YY

預期結果:? 1分expression-

    - xx.*?yy 

表達: xx。 ?yy | XX。 ZZ

預期結果: 2分expression-

   - xx.*?yy 

       - xx.*?zz 

表達: XX。 ?YY |(XX ZZ | AA * BB?。?)

預期結果: 2分expression-

   - xx.*?yy  

       - (xx.*?zz|aa.*?bb) -2 sub expression- 

         - xx.*?zz 

         - aa.*?bb 

回答

0

boost::regex將允許你提取標記(即括號內)子表達式:

#include <boost/regex.hpp> 
#include <iostream> 

int main() { 
    boost::regex r("xx.?yy|(xx.?zz|aa.*?bb)", boost::regex::save_subexpression_location); 
    for (unsigned i = 1; i < r.mark_count(); ++i) { 
    auto range = r.subexpression(i); 
    std::cout << std::string(range.first, std::next(range.second)) << '\n'; 
    } 
} 

這將提取標記的子表達(xx.*?zz|aa.*?bb),但要得到更精確的東西,你需要一個正則表達式解析器:Lightweight regex parser

+0

我的意思是問如何得到表達式除以「或」 – user1790461

+0

@ user1790461是的,您需要一個正則表達式解析器;這不是正則表達式實現提供的東西。 – ecatmur

相關問題