Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this regex match?

Tags:

regex

c++11

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++

like image 347
PinkTurtle Avatar asked Mar 05 '26 00:03

PinkTurtle


1 Answers

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
}
like image 101
Filip Roséen - refp Avatar answered Mar 08 '26 00:03

Filip Roséen - refp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!