Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

regex

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

#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!

like image 579
c_sharp Avatar asked Aug 27 '13 23:08

c_sharp


People also ask

What is unknown escape sequence in C?

Kabir Patel wrote: > warning: unknown escape sequence '\)' Backslash is used as an escaping character for C strings; if you'd like to include a character that you wouldn't normally be able to represent in a text file then you can use an escape code for it, for example: \t tab (ASCII 9) \n newline (ASCII 10) \r carriage ...

What is use of '\ r escape sequence in C?

\r stands for “Carriage Return”. It is one of the escape sequences which is used to add a carriage return to the text. It tells the terminal emulator to move the cursor to the start of the line, not to the next line, like \n. Furthermore, it allows overriding the current line of the terminal.

Is an escape sequence?

Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark (").


1 Answers

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:

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

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

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

#define to_find "^.*([.]dat)?"
like image 173
Sergey Kalinichenko Avatar answered Sep 22 '22 13:09

Sergey Kalinichenko