2

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;
}
vivek
  • 4,951
  • 4
  • 25
  • 33
  • are you using regex_match, or regex_search? – Tom Knapen Nov 24 '11 at 22:14
  • As I mentioned. It's `regex_match` – vivek Nov 24 '11 at 22:15
  • 1
    Sorry, my mistake. So the string you are matching can only be " +" or " -"? Because regex_match doesn't search in a string, is only checks wether or not the full string matches the specified regex. If you want to match part of a string, use regex_search – Tom Knapen Nov 24 '11 at 22:17
  • @TomKnapen The example I've given is a perfect match, so there should be no problem. – vivek Nov 24 '11 at 22:21
  • You should post the code, your problem is probably in your use of std::regex and not with the pattern itself. – SoapBox Nov 24 '11 at 22:27
  • @SoapBox I was thinking the same, so I have posted it. – vivek Nov 24 '11 at 22:29

4 Answers4

3

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);
SoapBox
  • 20,457
  • 3
  • 51
  • 87
1

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

" (\\+|-)"
Teemu Ikonen
  • 11,861
  • 4
  • 22
  • 35
  • Regexp is correct, but check from here if you're using the matcher correctly: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339 – Teemu Ikonen Nov 24 '11 at 22:29
1

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

dma_k
  • 10,431
  • 16
  • 76
  • 128
0

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

Andi T
  • 616
  • 7
  • 13