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

前端 未结 2 1899
野趣味
野趣味 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:45

    The compiler generates a warning because not every escape sequence has a meaning in C++. The list of valid escape sequences can be found here.

    However, regex expects you to escape '.' in order to literally match a '.' character instead of anything. To escape '.' in a regex pattern, you must add a single '\' character before it. But since a single '\' means an escape in c++, you need to put two backslashes: "\\". Therefore, the correct pattern is "^\\.".

提交回复
热议问题