PinkTurtle
PinkTurtle

Reputation: 7041

Why doesn't this regex match?

std::cout << std::regex_match(std::string("f 1/1/1 3/3/1 4/4/1"), std::regex("f \d+\/\d+\/\d+ \d+\/\d+\/\d+ \d+\/\d+\/\d+")); // -> 0

I expect the above regular-expression to match the given string, but it does not. What's wrong with it?

It does match on https://www.regex101.com/, and when tested in Notepad++

Upvotes: 3

Views: 173

Answers (1)

Filip Ros&#233;en
Filip Ros&#233;en

Reputation: 63902

There are two issues with your code, both related to invalid escape-sequences:

  1. "\d" is interpreted as an escape-sequence, the resulting string (passed to std::regex) will not contain what you expect — instead use "\\d" to properly get a slash followed by the letter d.

  2. "\/" is not a valid escape-sequence, and there really is no need for you to escape /, instead leave it as if ("/").


Working Example

#include <regex>
#include <iostream>
#include <string>
int main () {
  bool result = std::regex_match (
    std::string ("f 1/1/1 3/3/1 4/4/1"),
    std::regex  ("f \\d+/\\d+/\\d+ \\d+/\\d+/\\d+ \\d+/\\d+/\\d+")
  );

  std::cout << result << std::endl; // 1
}

Upvotes: 5

Related Questions