为什么std :: regex_match会返回true?

bri*_*e90 1 c++ regex visual-c++ c++11

有人可以向我解释 - 为什么这段代码会在std :: regex_match之后返回true?

std::regex reg("(-)?(\\d)\{0,5\}(.)?(\\d)\{0,10\}");
std::string str("--");
std::regex_match(str, reg);
Run Code Online (Sandbox Code Playgroud)

谢谢!

Avi*_*Raj 5

因为您将某些捕获组转为可选,而某些捕获组重复了零次或多次. (\\d)\{0,5\}重复前一个标记\\d0到5次.(-)?将捕获组转为可选.因此-符号可能会或可能不会发生..是正则表达式中的一个特殊元字符,它匹配除换行符(\n,\r)之外的任何字符.但在DOTALL模式下,dot也会与换行符匹配(在其他语言中).要匹配文字点,您需要将点放在字符类中,[.]或者您需要像点那样转义点\\.

     (-)?(\\d)\{0,5\}(.)?(\\d)\{0,10\}
      |               |
catures the first `-` | This captures the second `-`
Run Code Online (Sandbox Code Playgroud)

请注意,此正则表达式也匹配空字符串.

DEMO