C++正则表达式、未知转义序列'.'警告
C++ regex, unknown escape sequence '.' warning
我第一次尝试在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++中意味着转义,因此您需要放置两个反斜杠:"\\"。因此,正确的模式是"^\\."。
相关文章:
- 如何在C++中用'\'替换''来处理转义序列?
- 是否可以在原始字符串文本中插入转义序列?
- 使用无法适应其相关类型的转义序列
- C++二进制值的转义序列
- 使变量字符串忽略转义序列
- "Delete"的转义序列
- getchar() 避免转义序列
- GCC 编译时出现警告:未知转义序列:"\040"
- C++ 中转义序列的数据类型
- 如何在 QString 中解析转义序列
- "'"转义序列的目的是什么?
- C++ 无法识别的转义序列
- lex 中 OR ( | ) 的转义序列
- 转义序列?在 Qstring 中使用引号
- <<未找到运算符和无法识别的转义序列
- 调用 AINSI 转义序列时避免换行
- cmake 在窗口上生成错误,因为它使用 作为转义序列
- 如何分析具有原始转义序列的字符串
- 十六进制转义序列的最大长度
- C++正则表达式、未知转义序列'.'警告