C++ regex, unknown escape sequence '\.' warning

前端 未结 2 1902
野趣味
野趣味 2021-02-14 06:58

First time I tried using regular expressions in C++, and I\'m a little confused about escape sequences. I\'m simply trying to match a dot at the beginning of a string. For that

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-14 07:36

    When you write in your code a string literal:

    "^\\\."  
    

    your compiler will parse it according to the C++ rules to generate the string that will be used in your executable. For example if \n would be encountered the string in your executable would contain a newline instead. The "\\" is transformed into "\", but your compiler doesn't know how to handle "\." because there is no such escape sequence defined in C++.

    Escape sequences in which the character following the backslash is not listed (...) are conditionally-supported, with implementation-defined semantics.

    So the string you're looking for is with only two slashes:

    "^\\."
    

    which will be transformed by the compiler into:

    "^\."  
    

    And this is the regex you're looking for !

    Remark: GCC for example will transform an unknown escape sequence "\." into ".", so that 2 or 3 bakslashes will in reality produce the same result.

    Online demo

提交回复
热议问题