CPP:为什么下一个正则匹配不正确

Cpp: Why the next regex match is not correct?

本文关键字:不正确 为什么 下一个 CPP      更新时间:2023-10-16

我有下一个代码样本:

    std::string str("example1   ");
    std::smatch sm;
    std::regex e("[a-zA-Z_]+[0-9a-zA-Z_]*s*");
    if (std::regex_match(str, sm, e))
    {
        std::cout << "ok_match";
    }

它应该接受包括空间在内的一切,但事实并非如此。例如,如果字符串为:

std::string str("example1");

so" ok_match"将在屏幕上打印。为什么?

您尚未正确逃脱"s"序列。实际上,您的编译器应该向您显示

的警告
main.cpp: In function 'int main()':
main.cpp:9:16: warning: unknown escape sequence: 's'
   std::regex e("[a-zA-Z_][0-9a-zA-Z_]*s*");
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~

要代表诸如C 字符串中s之类的正则模式,您将需要逃脱后斜线,以便在字符串中获得字面的后斜线。详细说明:

  • "n"代表一个线路。您可能以前看过。
  • "\n"代表后斜线,其次是字母n
  • 在同一静脉中,"s"被编译器视为逃生序列,除了序列"s"实际上并不存在。
  • 您想要实际 backslash s,因此您需要编写 "\s":backsslash,然后是字母 s。反过来,std::regex将其理解为Whitespace的速记。

此程序应执行您要寻找的事情:

#include <regex>
#include <string>
#include <iostream>
int main()
{
  std::string str("example1   ");
  std::smatch sm;
  std::regex e("[a-zA-Z_][0-9a-zA-Z_]*\s*");
  if (std::regex_match(str, sm, e))
  {
    std::cout << "ok_match";
  }
}

活在Coliru