Home > Software engineering >  How to correctly use regular expressions from <regex> header in C ?
How to correctly use regular expressions from <regex> header in C ?

Time:10-26

I want to check version number eg 1.13.1 , 1.22.34 , 4.12.3 etc with regular expression using regex_match() from regex header.

I'm doing this way

#include <iostream>
#include <string>
#include <regex>
using namespace std;
 
int main () {
 
    if (regex_match ("1.14.1", regex("\d .\d .\d ") ))
   {    
       cout << "string:literal => matched\n";
    
   }
 
 
  
   return 0;
}

But I am not getting it matched ? It seems the regular expression is correct

CodePudding user response:

A backslash (\) escapes the next character in a const char literal.
That said, your escape sequences \d cannot be recognized correctly as regex matching pattern, because it expects a \ itself. A backslash can be represented in those literals, by escaping itself: \\, or using a raw string literal (see 2nd option).

regex("\d .\d .\d ")

Should be

regex("\\d .\\d .\\d ")

or

regex(R"(\d .\d .\d )")
  • Related