我第一次尝试在C++中使用正则表达式,我对转义序列有点困惑.我只是想在一个字符串的开头匹配一个点.为此,我使用了表达式:"^ \\\.",它有效,但我的编译器(g ++)生成一个警告:
warning: unknown escape sequence '\.'
regex self_regex("^\\\.");
^~
Run Code Online (Sandbox Code Playgroud)
如果我使用例如"^ \\.",它不会产生警告,但正则表达式与我打算做的不符.
我也不明白为什么我必须使用三个反斜杠,不应该两个就足够了,在"\"中.第一个反斜杠逃脱第二个,所以我实际上搜索.,但它不起作用.有人可以帮我澄清一下吗?
码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
Chr*_*phe 10
当您在代码中写入字符串文字时:
"^\\\."
Run Code Online (Sandbox Code Playgroud)
您的编译器将根据C++规则对其进行解析,以生成将在您的可执行文件中使用的字符串.例如,如果\n遇到,可执行文件中的字符串将包含换行符.将"\\"被改造成"\"的,但你的编译器不知道如何处理"\.",因为有没有这样的转义序列在C++中定义.
其中未列出反斜杠后面的字符(...)的转义序列是有条件支持的,具有实现定义的语义.
所以你要找的字符串只有两个斜杠:
"^\\."
Run Code Online (Sandbox Code Playgroud)
这将由编译器转换为:
"^\."
Run Code Online (Sandbox Code Playgroud)
备注:例如,GCC会将未知的转义序列"\."转换为".",因此2或3个bakslashes实际上会产生相同的结果.