Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ :Why the regular expression pattern"[+-/*]" matches string "."?

Tags:

c++

regex

What's wrong with the regular expression I used?

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

"." will be print out and if I use '\' to create escape sequence like:

string temp("[\\+-/\\*]");

The output remains.

like image 729
programforjoy Avatar asked Feb 09 '23 17:02

programforjoy


1 Answers

The problem is that - is interpreted differently inside character class [], covering characters in a range. This is the interpretation of - that lets you define [A-Z] to cover all upper-case letters, or [0-9] to cover all decimal digits.

If you want to use -, place it at the beginning or at the end of the block, or escape it with \:

string temp("[-+/*]");

Otherwise, [+-/] covers all characters with codes between '+' (43) and '/' (47), inclusive, i.e. '+', ',', '-', '.', and '/'.

like image 155
Sergey Kalinichenko Avatar answered Feb 16 '23 02:02

Sergey Kalinichenko