c++ - 正则表达式在 g++ 4.9 下匹配但在 g++-5.3.1 下失败

标签 c++ regex c++11 g++

我正在用正则表达式标记一个字符串;这在 g++-4.9 下正常工作,但在 g++-5.3.1 下失败。

我有以下 txt 文件:

0001-SCAND ==> "Scandaroon" (from Philjumba)
0002-KINVIN ==> "King's Vineyard" (from Philjumba)
0003-HANNI ==> "Hannibal: Rome vs. Carthage" (from Philjumba)
0004-LOX ==> "Lords of Xidit" (from Philjumba)

我正在使用正则表达式、空格、引号对和括号对对其进行标记化。例如,第一行应该标记如下:

0001-SCAND
==>
"Scandaroon"
(from Philjumba)

我写了下面的std::regex:

std::regex FPAT("(\\S+)|(\"[^\"]*\")|(\\([^\\)]+\\))";

我用以下方法标记字符串:

std::vector<std::string>
split( const std::string & input, const std::regex & regex ) {

        std::sregex_token_iterator
                first{input.begin(), input.end(), regex, 0},
                last;

        return {first, last};
}

这将返回匹配项。在 g++-4.9 下,字符串按要求进行标记化,但在 g++-5.3.1 下,它的标记化如下:

0001-SCAND
==>
"Scandaroon"
(from
Philjumba)

或者第三行标记化如下:

0003-HANNI
==>
"Hannibal:
Rome
vs.
Carthage"
(from
Philjumba)

可能是什么问题?


编辑:我按如下方式调用函数:

std::string line("0001-SCAND ==> \"Scandaroon\" (from Philjumba)");
auto elems = split( line, FPAT );

编辑:根据@xaxxon 的反馈,我用 vector 替换了返回迭代器,但它在 g++-5.3 下仍然无法正常工作。

std::vector<std::string>
split( const std::string & input, const std::regex & regex ) {

        std::sregex_token_iterator
                first{input.begin(), input.end(), regex, 0},
                last;

        std::vector< std::string > elems;
        elems.reserve( std::distance(first,last) );

        for ( auto it = first; it != last; ++ it ) {
                //std::cout << (*it) << std::endl;
                elems.push_back( *it );
        }

        return elems;
}

最佳答案

正则表达式渴望

因此对于正则表达式 "Set|SetValue" 和文本 "SetValue",正则表达式找到 "Set"

你必须仔细选择顺序:

std::regex FPAT(R"(("[^\"]*\")|(\([^\)])+\)|(\S+))");

\S+ 最后考虑。

另一种选择是不使用默认选项(参见 http://en.cppreference.com/w/cpp/regex/syntax_option_type ) 并使用 std:::::regex::extended

std::regex FPAT(R"((\S+)|("[^\"]*\")|(\([^\)])+\))", std::::regex::extended);

看来 g++-5.3.1 已经修复了 g++-4.9 之后的一个 bug。

关于c++ - 正则表达式在 g++ 4.9 下匹配但在 g++-5.3.1 下失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37147546/

相关文章:

regex - git 提交中的 SLOC

c++ - 如何检查模板参数是否是具有给定签名的可调用对象

非 C++11 程序中的 C++11 代码/库

c++ - 带有部分参数包的可变辅助函数

c++ - 在 std::pair 支撑初始化中复制 vs move

c++ - 我怎样才能有可选的默认构造函数?

regex - 使用 Awk 使用正则表达式和循环对字段求和

c++ - 音频处理 - 音调识别

c++ - 在不创建新节点的情况下使用 map 实现 trie

php - 定期将分隔符插入字符串