Mr Ashi Iq
Mr Ashi Iq

Reputation: 1

A regex_match is not working as expected

This is my code:

#include <iostream>
#include <string.h>
#include <regex>

using namespace std;

int main () {

    string test = "COPY" ;
    regex r1 = regex ("(COPY\b)(.*)") ; 
    if (regex_match (test,r1) ) {
        cout << "match !!" ;
    } else {
        cout << "not match !!";
    }

Ok , I thought that this code print me "match !!" , and that is what I wanted.
But , it give me a "not match !!"
What should I do ?

notice:
I want "COPY" to match, but not "COPYs" or "COPYYY", because of it I used "\b" in my code.

Upvotes: 0

Views: 217

Answers (2)

Ofir Farchy
Ofir Farchy

Reputation: 8027

Firstly, fix your brackets (with the if statement).

Secondly try:

regex r1 = regex ("(COPY)(\\b|$)") ;

This will look for 'COPY' followed either by a word break or at the end of the string.

Meaning your code should look like:

#include <iostream>
#include <string.h>
#include <regex>

using namespace std ;

int main () {

    string test = "COPY" ;
    regex r1 = regex ("(COPY)(\\b|$)") ; 
    if (regex_match (test,r1) ) {
        cout << "match !!" ;
    } else {
        cout << "not match !!";
    }
}

Upvotes: 1

Kevin Anderson
Kevin Anderson

Reputation: 7010

You need to double-escape your \b because the \ character is the "escape" sequence in C/C++, like when putting a newline, you use \n even though that's ONE character, not two. So your expression goes from this: "(COPY\b)(.*)" to this: "(COPY\\b)(.*)".

For the extreme case, if you want to match a \ character in a regex, you need this: "\\\\" because the \ character is also the escape character, thus you're escaping the escape.

FYI this is why in .NET they often use their raw string syntax for regular expressions, then you don't need to escape it. Some other languages don't have this as the escape character, and so regex is easier.

Upvotes: 2

Related Questions