我想在boost正则表达式或cpp中的任何其他替代方法中实现以下perl评估。
#!/usr/bin/perl
use strict;
use warnings;
my $regex_pattern = "/^rst/i";
my $name = "rst";
my $match;
my $tmpRegExp = "\$match = (\$name =~ $regex_pattern);";
eval ($tmpRegExp);
if(!$match) {
print "not matched\n";
} else {
print "matched\n";
}
Perl coutput
% perl perl_regex.pl
matched
我试过下面的示例代码
#include <boost/regex.hpp>
#include <string>
#include <iostream>
int main()
{
std::string regex_pattern("/^rst/i");
std::string name("rst");
boost::regex regex_expr(regex_pattern, boost::regex::perl);
bool match = boost::regex_search(name, regex_expr);
if(match)
std::cout << "matched" << std::endl;
else
std::cout << "not matched" << std::endl;
return 0;
}
C ++输出
% g++ boost_regex.cpp -l boost_regex
% ./a.out
not matched
但这不符合预期。我预计“匹配”也应该是boost版本的结果。这个regex_pattern是一个perl regex用户变量。 有人可以帮忙,错误在哪里?
答案 0 :(得分:2)
根据Boost正则表达式功能的this example in the documentation,模式周围不应该有斜杠,并且您不能像使用模式创建运算符m//
那样将模板传递给模式字符串中的模式。在Perl。
regex expression("^([0-9]+)(\\-| |$)(.*)$");
Boost's documentation about PCRE表示默认情况下,模式区分大小写。这支持了我的假设,即您无法在模式本身内传递/i
之类的标记。相反,您需要将它作为标志传递给模式构造函数的第二个参数,如SYNOPSIS所示。
// e2 a case insensitive Perl regular expression:
boost::regex e2(my_expression, boost::regex::perl|boost::regex::icase);
Boost中的PCRE标志的完整列表可用here。请注意,并非所有这些都映射到当前Perls中m//
或s///
上的实际修饰符标记,如perlre中所述。这是因为PCRE 不是 Perl,而是 Perl兼容正则表达式引擎。
答案 1 :(得分:1)
自C ++ 11以来,有一种标准的Regex机制。 我个人更喜欢这个过度提升或任何其他第三方库。当然这只是我自己的意见。
如果要使用C ++ 11附带的实用程序,可以执行以下操作
#include <iostream>
#include <string>
#include <regex>
int main(int argc, char** argv)
{
std::string input = "rst";
std::regex regex_pattern("^rst", std::regex_constants::icase); // use ::icase to make the matching case insensitive like /i in perl
if ( std::regex_match(input, regex_pattern) )
{
std::cout << "matched!\n";
}
else
{
std::cout << "not matched!\n";
}
return 0;
}