2012-07-04 96 views
1

我正在使用boost :: regex_match,並試圖找到一個函數來獲取正則表達式停止匹配的位置。我在boost :: match_results對象中找不到任何屬性,但有幾個代碼片段使用boost :: regex_search來顯示子匹配。我是否在正確的道路上執行了自己的實施,還是爲了實現這個目標,我需要做些不同的事情?我的代碼如下:在boost匹配結果中查找不匹配

int main(int args, char** argv) 
{ 
    boost::match_results<std::string::const_iterator> what; 

    if(args == 3) 
    { 
     std::string text(argv[1]); 
     boost::regex expression(argv[2]); 

     std::cout << "Text : " << text << std::endl; 
     std::cout << "Regex: " << expression << std::endl; 

     if(boost::regex_match(text, what, expression, boost::match_default) != 0) 
     { 
      int i = 0; 

      for(boost::match_results<std::string::const_iterator>::const_iterator it=what.begin(); it!=what.end(); ++it) 
      { 
       std::cout << "[" << (i++) << "] " << it->str() << std::endl; 
      } 
      std::cout << "Matched!" << std::endl; 
     } 
     else 
     { 
      std::string::const_iterator start = text.begin(); 
      std::string::const_iterator end = text.end(); 

      while(boost::regex_search(start, end, what, expression)) 
      { 
       std::string submatch(what[1].first, what[1].second); 
       std::cout << submatch << std::endl; 
       start = what[0].second; 
      } 
      std::cout << "Didn't match!" << std::endl; 
     } 
    } //if(args == 3) 
    else 
    { 
     std::cout << "Invalid usage! $> ./boost-regex <text> <regex>" << std::endl; 
    } 
    return 0; 
} 

輸出:

$> ./boost_regex "We're building it up to burn it down" ".*(build.*)(to.*)(burn.*)" 
Text : We're building it up to burn it down 
Regex: .*(build.*)(to.*)(burn.*) 
[0] We're building it up to burn it down 
[1] building it up 
[2] to 
[3] burn it down 
Matched! 

$> ./boost_regex "We're building it up to burm it down" ".*(build.*)(to.*)(burn.*)" 
Text : We're building it up to burm it down 
Regex: .*(build.*)(to.*)(burn.*) 
Didn't match! 

在過去的輸入我想有類似的東西:

Text : We're building it up to burm it down 
Regex: .*(build.*)(to.*)(burn.*) 
[0] We're building it up to 
[1] building it up 
[2] to 
Didn't match! 

在此先感謝...

回答

1

首先,你的例子中的正則表達式有問題。因爲它不能匹配(burn.*)子組,所以整個正則表達式無法匹配任何內容,並且不會返回任何結果。添加「?」在(burn.*)之後會使得前兩個子組匹配,而第三個子組不會匹配。

我會checkout rubular.com,這是一個很好的工具,用於調整正則表達式並觀察它們是否實時工作。

要測試子組是否參與匹配,您需要檢查for循環中的sub_match::matched布爾變量,如果子組匹配,則該值爲true。檢查提升文檔:: submatch here

希望這有幫助,它實際上是我的第一個Stackoverflow的帖子,答案或評論。 :)

+0

你是正確的正則表達式,我看到它與regextester.com和我的應用程序呢!您是否有建議可以實現上述行爲的正則表達式?我嘗試過,但找不到任何=(目標是看看哪個部分匹配,哪個沒有匹配!完全像是用boost :: spirit :: parse_info :: stop確定的。 – janr

+0

好的,我找到了這是一個適合我的應用領域的正則表達式,你已經用「?」來提到它,但我沒有提出正確的正則表達式,它看起來如下(隨時迴應改進):(我們)?('重新)?[\ S \ n]的{0,}(建築物)?[\ S \ n]的{0,}(它)?[\ S \ n]的{0,}(上)?[\ S \ n ] {0,}(至)?[\ S \ n]的{0,}(燒傷)?[\ S \ n]的{0,}(它)?[\ S \ n]的{0,}(下) ?[\ s \ n] {0,} – janr

+1

@janr我可能是錯的,但我認爲你可以用「*」代替「{0,}」,只用「\ s」而不是「\ s \ n」,它們分別表示相同的東西,所以你可以這樣做:'(We)?('re)?[\ s] *(building)?[\ s](it) ?[\ s] *(上)?[\ S] *(於)?[\ S] *(燒)?[\ S] *(它)?[\ S] *(下)?[\ S ] *'。 – ki4jnq