C++ Regex to match '+' quantifier

假装没事ソ 提交于 2021-01-27 18:33:57

问题


I want to match expression of the pattern

a space followed by a (addition operator or subtraction operator)

For example: " +" should return True

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

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

but they all return false.

What should be the correct expression ?

EDIT

Here's the test code:

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

回答1:


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

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

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.

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);



回答2:


Try this, it matches the string with whitespace followed by one + or -.

" (\\+|-)"



回答3:


Usually the minus sign is required to go first: [-abc]. This is because not to mix with ranges [a-b].




回答4:


You could try as I think it should work but I haven't tested it yet: " [\+-]"



来源:https://stackoverflow.com/questions/8262889/c-regex-to-match-quantifier

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!