Using Visual Studio Community 2015 C++ Unexpected results using
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'
Expected results:
Found Match 0 'f=12/64' Found Match 1 'f' Found Match 2 '12' Found Match 3 '64'
Commentary:
The regex works correctly on multiple other regex systems including C, Perl, Java, and 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. The cm[idxMatch]
is not a null-terminated string, thus the %s
specifier will not work. 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.
Live Example Using Visual Studio 2015 and std::cout
To round things out, here is your example using printf
. Note the weirdness that is outputted:
Here is printf weirdness and Visual Studio 2015
Edit: For g++, there is a runtime error when using printf
.
while using std::cout
, we get the desired output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.