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.)
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 R
aw 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With