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

C++ regex, unknown escape sequence '.' warning

本文关键字:警告 转义序列 正则表达式 未知 C++      更新时间:2023-10-16

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

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

如果我使用例如"^\\.",它不会生成警告,但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,可执行文件中的字符串将包含换行符。"\"被转换为"",但编译器不知道如何处理".",因为C++中没有定义这样的转义序列。

反斜杠后面的字符为的转义序列有条件地支持未列出的(…)实现定义的语义。

所以你要找的字符串只有两个斜杠:

"^\."

编译器将其转换为:

"^."  

这就是您要查找的正则表达式!

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

在线演示

编译器生成警告,因为并非每个转义序列在C++中都有意义。有效转义序列的列表可以在这里找到。

但是,regex希望您转义"为了真正匹配一个"。"性格而不是任何东西。逃离"。"在正则表达式模式中,您必须在其前面添加一个"\"字符。但是由于单个"\"在c++中意味着转义,因此您需要放置两个反斜杠:"\\"。因此,正确的模式是"^\\."。