C++:为什么正则表达式模式"[+ - /*]"匹配字符串"."?

pro*_*joy 4 c++ regex

我使用的正则表达式有什么问题?

#include<regex>
#include<iostream>
#include<string>
using namespace std;
int main(int argc,char *argv[])
{
    smatch results;
    string temp("[+-/*]");
    string test(".");

    regex r(temp);

    if(regex_search(test,results,r))
        cout<<results.str()<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

"" 将打印输出,如果我使用'\'创建转义序列,如:

string temp("[\\+-/\\*]");
Run Code Online (Sandbox Code Playgroud)

输出仍然存在.

das*_*ght 8

问题是-在字符类中对其进行不同的解释[],涵盖范围内的字符.这是对它的解释-,允许您定义[A-Z]覆盖所有大写字母,或[0-9]覆盖所有小数位数.

如果要使用-,请将其放在块的开头或末尾,或者使用以下命令将其转义\:

string temp("[-+/*]");
Run Code Online (Sandbox Code Playgroud)

否则,[+-/]涵盖与代码之间的所有字符'+'和(43)'/'(47),其中包括的,即'+',',','-','.',和'/'.