C++正则表达式以匹配'+'量词

C++ Regex to match '+' quantifier

本文关键字:量词 正则表达式 C++      更新时间:2023-10-16

我想匹配的表达式模式

一个空格后面跟一个(加减运算符)

例如

:" +"应该返回True

我已经尝试使用std::regex_match对以下常规exp:

" [+-]", "\s[+-]", "\s[+\-]", "\s[\+-]"

但是它们都返回false

正确的表达式是什么?

编辑

下面是测试代码:
#include<iostream>
#include<string>
#include<regex>
using std::cout;
int main()
{
    std::string input;
    std::cin>>input;
    const std::regex ex(" [\+-]");
    std::smatch m;
    if( std::regex_match(input,ex))
    {
        cout<<"nTrue";
    }
    else
        cout<<"nFalse";
    return 0;
}

现在您已经发布了代码,我们可以看到问题所在:

std::string input;
std::cin >> input;

问题在这里,operator >>在读取时跳过空白,所以如果您输入space plus, cin将跳过空格,然后您的正则表达式将不再匹配。

要使这个程序工作,使用std::getline来读取用户按enter之前输入的所有内容(包括空格):

std::string input;
std::getline(std::cin, input);

试试这个,它用空格后面跟着一个+或-匹配字符串。

" (\+|-)"

通常需要在前面加上减号:[-abc]。这是因为不能与范围[a-b]混合使用。

你可以尝试,因为我认为它应该工作,但我还没有测试它:" [+-]"