C语言 C 编译器警告未知转义序列 '\.' c程序中使用正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18477153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:17:31  来源:igfitidea点击:

C compiler warning Unknown escape sequence '\.' using regex for c program

cregex

提问by c_sharp

I am using regex to determine a command line argument has the .dat extension. I am trying the following regex:

我正在使用正则表达式来确定命令行参数具有 .dat 扩展名。我正在尝试以下正则表达式:

#define to_find "^.*\.(dat)?"

For some reason I am getting the warning I stated in the title of this question. First, is this expression correct? I believe it is. Second, if it is correct, how can i get rid of this warning?

出于某种原因,我收到了我在这个问题的标题中提到的警告。首先,这个表达是否正确?我相信是的。其次,如果它是正确的,我怎样才能摆脱这个警告?

I am coding a c program in Xcode and the above #define is in my .h file. Thanks!

我正在 Xcode 中编写 ac 程序,上面的 #define 在我的 .h 文件中。谢谢!

回答by dasblinkenlight

The warning is coming from the C compiler. It is telling you that \.is not a known escape sequence in C. Since this string is going to a regex engine, you need to double-escape the slash, like this:

警告来自 C 编译器。它告诉您这\.不是 C 中已知的转义序列。由于此字符串将进入正则表达式引擎,因此您需要对斜杠进行双重转义,如下所示:

#define to_find "^.*\.(dat)?"

This regex would match a string with an optional .datextension, with datbeing optional. However, the dot .is required. If you want the dot to be optional as well, put it inside the parentheses, like this: ^.*(\\.dat)?.

此正则表达式将匹配具有可选.dat扩展名的字符串,并且dat是可选的。但是,点.是必需的。如果你想点是可选的还有,把它放在括号内,像这样:^.*(\\.dat)?

Note that you can avoid escaping the individual metacharacters by enclosing them in square brackets, like this:

请注意,您可以通过将单个元字符括在方括号中来避免转义它们,如下所示:

#define to_find "^.*([.]dat)?"

回答by Ed Heal

You need

你需要

#define to_find "^.*\.(dat)?"

Should do the trick as the \ needs to be escaped for C and not the benefit for regex at this stage

应该做到这一点,因为 \ 需要为 C 转义,而不是现阶段正则表达式的好处