Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex statement in C++ isn't working as expected [duplicate]

Tags:

c++

regex

The below regex statement matches when using perl, but it doesn't match when using c++. After reading the "std::regex" class information on cplusplus.com, I might have to use regex_search instead. That's unless, I use the flags within the regex_match. Using the regex_search seems to over complicate a simple match I want to perform. I would like to have the match on 1 line similar to perl. Is there another 1 line approach for performing regex matches in c++?

c++

std::string line1 = "interface GigabitEthernet0/0/0/3.50 l2transport";
if (std::regex_match(line1, std::regex("/^(?=.*\binterface\b)(?=.*\bl2transport\b)(?!.*\.100)(?!.*\.200)(?!.*\.300)(?!.*\.400).*$/")))
cout << line1;

perl

my $line1 = "interface GigabitEthernet0/0/0/3.50 l2transport";
if ($line1 =~ /^(?=.*\binterface\b)(?=.*\bl2transport\b)(?!.*\.100)(?!.*\.200)(?!.*\.300)(?!.*\.400).*$/ )
    print $line1;

I could create a method and pass the search criteria to return a true or false....

(Note: the reason i want to use C++ is because its much faster) interpreted vs compiled

(Update 2017-05-16: C++ wasn't faster than Perl in this example. The speed of your script just depends on how you arrange your code in either language. In my case, Perl was actually faster than C++ in this scenario. Both languages used regex and the same type of layouts. C++ seemed extremely slower even when I used the boost library.)

like image 660
Jelani Avatar asked Dec 15 '22 02:12

Jelani


1 Answers

As others have mentioned, you don't need the two forward slashes when you write regex in C++. I will also add another solution which is that you can use a Raw String literal to write the regex.

For example:

std::string line1 = "interface GigabitEthernet0/0/0/3.50 l2transport";
std::regex pattern (R"(^(?=.*\binterface\b)(?=.*\bl2transport\b)(?!.*\.100)(?!.*\.200)(?!.*\.300)(?!.*\.400).*$)");
if (std::regex_match(line1, pattern)) {
    std::cout << line1 << '\n';
}

By using a raw string, you prevent C++ from interpreting the escaped characters inside the string therefore your regex is left intact.

like image 150
smac89 Avatar answered Jan 04 '23 22:01

smac89