2012-03-05 62 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