简体   繁体   English

C ++正则表达式Visual Studio社区2015 <regex> 出乎意料的结果

[英]C++ regex Visual Studio Community 2015 <regex> gives unexpected results

Using Visual Studio Community 2015 C++ Unexpected results using 使用Visual Studio Community 2015 C ++使用的意外结果

Source code: 源代码:

#include <regex>
int main()
{
    std::regex re("^(.)=(\\d{1,2})/(\\d{1,2})*$");
    std::cmatch cm;
    std::regex_match("f=12/64", cm, re);
    for (unsigned idxMatch = 0; idxMatch < cm.size(); idxMatch++)
    {
        printf("Found Match %d '%s'\n", idxMatch, cm[idxMatch]);
    }
    return 0;
}

Results: 结果:

Found Match 0 'f=12/64' Found Match 1 'f=12/64' Found Match 2 '12/64' Found Match 3 '4' 找到匹配0'f = 12/64'找到匹配1'f = 12/64'找到匹配2'12 / 64'找到匹配3'4'

Expected results: 预期成绩:

Found Match 0 'f=12/64' Found Match 1 'f' Found Match 2 '12' Found Match 3 '64' 找到匹配0'f = 12/64'找到匹配1'f'找到对第2'12'找到对应3'64'

Commentary: 评论:

The regex works correctly on multiple other regex systems including C, Perl, Java, and Javascript. 正则表达式在多个其他正则表达式系统上正常工作,包括C,Perl,Java和Javascript。

The regex works correctly on every multiple online tester that I attempted. 正则表达式在我尝试的每个多个在线测试器上都能正常工作。

I have tried escaping the "/" with unexpectedly identical results. 我试图以意想不到的相同结果转义“/”。

I found no clues to possible incorrect regex at the Microsoft website. 我在微软网站上找不到可能不正确的正则表达式的线索。

The issue is that you are using printf with wrong format specifiers. 问题是您使用的printf格式说明符错误。 The cm[idxMatch] is not a null-terminated string, thus the %s specifier will not work. cm[idxMatch]不是以null结尾的字符串,因此%s说明符不起作用。 The behavior is undefined when you provide the wrong data type to match the output specifier. 当您提供错误的数据类型以匹配输出说明符时,行为是未定义的。

The easiest solution is to use std::cout , and typesafe output streams in general. 最简单的解决方案是使用std::cout和typesafe输出流。

Live Example Using Visual Studio 2015 and std::cout 使用Visual Studio 2015和std :: cout的实例

To round things out, here is your example using printf . 为了解决问题,这是使用printf的示例。 Note the weirdness that is outputted: 注意输出的怪异:

Here is printf weirdness and Visual Studio 2015 这是printf怪异和Visual Studio 2015


Edit: For g++, there is a runtime error when using printf . 编辑:对于g ++,使用printf时会出现运行时错误。

g++ printf runtime error g ++ printf运行时错误

while using std::cout , we get the desired output: 使用std::cout ,我们得到了所需的输出:

g++ using std::cout g ++使用std :: cout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM