提升正则表达式与选项卡不匹配

Boost regex don't match tabs

本文关键字:不匹配 选项 正则表达式      更新时间:2023-10-16

我使用的是boost regex_match,在不匹配制表符时遇到问题。我的测试应用程序如下所示:

#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

在这种情况下,我本以为what[0].matched是false,但事实并非如此。

我的正则表达式有错吗
或者我必须使用其他格式/匹配标志吗?

提前谢谢!

我不确定你想做什么。我的理解是,你希望regex在文本中出现选项卡后立即失败。

您的正向前瞻断言(?=.*[^t])在找到非制表符时即为true,并且您的文本中有很多非制表符。

如果你想让它失败,当有一个选项卡时,可以反过来使用否定的前瞻性断言。

(?!.*t).*

一旦找到选项卡,此断言就会失败。