C ++中的Regex陈述式无法正常运作 [英] Regex statement in C++ isn't working as expected

查看:44
本文介绍了C ++中的Regex陈述式无法正常运作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的regex语句在使用perl时匹配,但是在使用c ++时不匹配.阅读cplusplus.com上的"std :: regex"类信息后,我可能不得不改用regex_search.除非我在regex_match中使用这些标志.使用regex_search似乎使我想要执行的简单匹配复杂化了.我想在与perl类似的1行上进行匹配.在C ++中还有另一种用于执行正则表达式匹配的方法吗?

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;

我可以创建一个方法并通过搜索条件以返回true或false....

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

(注意:我想使用C ++的原因是因为它速度更快)解释与编译的结果

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

(更新2017-05-16:在此示例中,C ++并不比Perl快.脚本的速度仅取决于您以两种语言排列代码的方式.就我而言,Perl实际上比C ++快.在这种情况下,两种语言都使用了正则表达式和相同类型的布局.即使我使用boost库,C ++的速度也非常慢.)

(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.)

推荐答案

就像其他人提到的那样,用C ++编写正则表达式时不需要两个正斜杠.我还将添加另一种解决方案,即您可以使用 R aw String 文字以编写正则表达式.

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.

例如:

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

通过使用原始字符串,可以防止C ++解释字符串中的转义字符,因此您的正则表达式保持不变.

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

这篇关于C ++中的Regex陈述式无法正常运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆