gpt4 book ai didi

C++ 正则表达式,未知转义序列 '\.' 警告

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:09:27 35 4
gpt4 key购买 nike

我第一次尝试在 C++ 中使用正则表达式,我对转义序列有点困惑。我只是想匹配字符串开头的点。为此,我使用了表达式:“^\\\.”,它有效,但我的编译器 (g++) 生成警告:

warning: unknown escape sequence '\.'
regex self_regex("^\\\.");
^~

如果我使用例如“^\\.”,它不会生成警告,但该正则表达式与我打算做的不匹配。

我也不明白为什么我必须在“\”中使用三个反斜杠,两个就足够了吗?第一个反斜杠转义了第二个反斜杠,所以我实际上搜索了 .,但它不起作用。有人可以为我澄清一下吗?

代码:

#include <iostream>
#include <dirent.h>
#include <regex>

using namespace std;

int main(void){
DIR *dir;
string path = "/Users/-----------/Documents/Bibliothek/MachineLearning/DeepLearning/ConvolutionalNeuralNetworks/CS231n 2016/Assignments/assignment3/assignment3/cs231n";
regex self_regex("^\\\.+");
struct dirent *ent;
dir = opendir(path.c_str());
if ((dir = opendir(path.c_str())) != NULL){
while ((ent = readdir(dir)) != NULL){
if (regex_search(string(ent->d_name),self_regex)){
cout << "matches regex" << ent->d_name << endl;
}
else{
cout << "does not match regex " << ent->d_name << endl;
}
}
closedir(dir);
}
return 0;
}

输出:

matches regex.
matches regex..
matches regex.DS_Store
matches regex.gitignore
does not match regex __init__.py
does not match regex __init__.pyc
does not match regex build
does not match regex captioning_solver.py
does not match regex captioning_solver.pyc
does not match regex classifiers
does not match regex coco_utils.py
does not match regex coco_utils.pyc
does not match regex data_utils.py
does not match regex datasets
does not match regex fast_layers.py
does not match regex fast_layers.pyc
does not match regex gradient_check.py
does not match regex gradient_check.pyc
does not match regex im2col.py
does not match regex im2col.pyc
does not match regex im2col_cython.c
does not match regex im2col_cython.pyx
does not match regex im2col_cython.so
does not match regex image_utils.py
does not match regex image_utils.pyc
does not match regex layer_utils.py
does not match regex layers.py
does not match regex layers.pyc
does not match regex optim.py
does not match regex optim.pyc
does not match regex rnn_layers.py
does not match regex rnn_layers.pyc
does not match regex setup.py

最佳答案

当您在代码中写入字符串文字时:

"^\\\."  

您的编译器将根据 C++ 规则对其进行解析,以生成将在您的可执行文件中使用的字符串。例如,如果遇到 \n,则可执行文件中的字符串将包含换行符。 "\\" 被转换为 "\",但是你的编译器不知道如何处理 "\.",因为有no such escape sequence在 C++ 中定义。

Escape sequences in which the character following the backslash is not listed (...) are conditionally-supported, with implementation-defined semantics.

因此您要查找的字符串只有两个斜杠:

"^\\."

将被编译器转换成:

"^\."  

这是 regex you're looking for !

备注:例如 GCC 会将未知的转义序列 "\." 转换为 ".",因此 2 或 3 个 bakslashes 实际上会产生相同的结果.

Online demo

关于C++ 正则表达式,未知转义序列 '\.' 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38717526/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com