2012-03-05 61 views
0

我正在使用boost regex_match,並且在匹配沒有製表符時出現問題。 我的測試應用程序如下所示:Boost正則表達式與標籤不匹配

#include <iostream> 
#include <string> 
#include <boost/spirit/include/classic_regex.hpp> 

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; 

     std::cout << text; 

     if(what[0].matched) 
      std::cout << " matches with regex pattern!" << std::endl; 
     else 
      std::cout << " does not match with regex pattern!" << std::endl; 

     for(boost::match_results<std::string::const_iterator>::const_iterator  it=what.begin(); it!=what.end(); ++it) { 
      std::cout << "[" << (i++) << "] " << it->str() << std::endl; 
     } 
     } else { 
     std::cout << "Expression does not match!" << std::endl; 
     } 
    } else { 
    std::cout << "Usage: $> ./boost-regex <text> <regex>" << std::endl; 
    } 

    return 0; 
} 

如果我運行這些參數的程序,我沒有得到期望的結果:

$> ./boost-regex "`cat file`" "(?=.*[^\t]).*" 
Text : This  text includes some tabulators 
Regex: (?=.*[^\t]).* 
This text includes some tabulators matches with regex pattern! 
[0] This  text includes some tabulators 

在這種情況下,我會預計什麼[0]。匹配的是錯誤的,但事實並非如此。

我的正則表達式有任何錯誤嗎?
還是我必須使用其他格式/比賽標誌?

預先感謝您!

+4

您給程序的實際文本沒有任何標籤,就像您在輸出中看到的那樣(它顯示文本「\ t」而不是打印實際標籤)。 – 2012-03-05 12:08:41

+0

這是正確的,我只想示範一個簡短的例子!我正在使用包含標籤的文本文件(使用hexdump進行驗證 - > 0x09)。我糾正了我的例子! – janr 2012-03-05 12:19:55

回答

2

我不確定你想要做什麼。我的理解是,只要文本中有一個標籤,就希望正則表達式失敗。

只要發現一個非選項卡,並且文本中有很多非選項卡,則您的積極預見聲明(?=.*[^\t])就是正確的。

如果你想讓它失敗,當有一個選項卡時,反過來並使用負向視向斷言。

(?!.*\t).* 

這個斷言一旦找到標籤就會失敗。

+0

這工作,非常感謝! – janr 2012-03-05 13:09:33