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

后端 未结 2 597
余生分开走
余生分开走 2021-02-18 22:18

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

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

相关标签:
2条回答
  • 2021-02-18 22:35

    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)?"
    
    0 讨论(0)
  • 2021-02-18 22:38

    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

    0 讨论(0)
提交回复
热议问题