CPP:为什么下一个正则匹配不正确
Cpp: Why the next regex match is not correct?
我有下一个代码样本:
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
相关文章:
- 为什么除非我使用 cout,否则我的值不正确?
- 为什么 sizeof 在 C++ 中给出不正确的字节数?
- 为什么我的位移给出不正确的数字
- 为什么我的子集和方法不正确?
- C++ - 为什么 unicode 输出不正确?
- 为什么要 boost::p roperty_tree::write_json() 将整数值转换为字符串?这是不正确的
- 为什么在template函数广播中把两个extensor表达式加在一起不正确
- 为什么以下变量分配不正确
- 为什么不调用预期的函数?我是否对类型特征的理解不正确?
- 为什么当我使用双精度时,Qt<->Matlab 正确写入和读取我的字节,但存储 uint32 的字节不正确?
- 为什么参考简历的格式不正确?
- 为什么构造函数C++接受不正确的类型作为参数?
- 为什么我的二维表不正确显示
- 为什么这里打印的复数不正确?
- 为什么 (int&)0 格式不正确?
- 为什么我的getline不正确读取.csv文件
- 为什么 SDL2 提供的事件值不正确
- 为什么我的OpenSSL / libcrypto签名不正确
- 为什么隐式类型转换在此代码中结果不正确
- 我的假设是下面的代码不正确的NDR?但为什么