plasmacel
plasmacel

Reputation: 8530

C++11 regex pattern match

Given an ECMAScript regex I'm trying to test a string against the specified pattern. For example the string "+0.1" should pass the test. However the result of std::regex_match is false.

#include <regex>
#include <string>

std::regex format("^[+-]?\d{1,3}\.?\d?$");
std::string str = "+0.1";

bool match = std::regex_match(str, format); // false

I have also tested the regex pattern on regexr and it works.

So what do I wrong?

Upvotes: 1

Views: 315

Answers (1)

milleniumbug
milleniumbug

Reputation: 15804

Backslash in \. and \d is treated as an escape character of C++ string literals.

Either use raw string literals (R"***(^[+-]?\d{1,3}\.?\d?$)***") or escape the backslashes like this "^[+-]?\\d{1,3}\\.?\\d?$"

Live On Coliru

Upvotes: 7

Related Questions