C ++正则表达式以匹配'+'量词 [英] C++ Regex to match '+' quantifier

查看:84
本文介绍了C ++正则表达式以匹配'+'量词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要匹配模式的表达方式

I want to match expression of the pattern

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

例如:"+" 应该返回 True

我已尝试在以下常规exp上使用 std :: regex_match :

I have tried the using std::regex_match on the following regular exp:

"[+-]" "\\ s [+-]" "\\ s [+ \\-]" ,<代码>"\\ s [\\ +-]"

但是它们都返回false.

but they all return false.

正确的表达式应该是什么?

What should be the correct expression ?

编辑

这是测试代码:

#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;
}

推荐答案

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

Now that you've posted code, we can see what the problem is:

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

问题出在这里, operator>> 在读取时会跳过空格,因此,如果键入空格加号,cin将跳过该空格,然后您的正则表达式将不再匹配.

The problem is here, operator >> skips whitespace when it reads, so if you type space plus, cin will skip the space and then your regex will no longer match.

要使该程序正常运行,请使用 std :: getline 来读取用户按下Enter键之前输入的所有内容(包括空格):

To get this program to work, use std::getline instead to read everything that was input before the user pressed enter (including spaces):

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

这篇关于C ++正则表达式以匹配'+'量词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆