How do you print a std::regex?
Asked Answered
F

1

12

How do you print the string representation of a std::regex?

Say I have a collection of patterns, and I'd like to print the first one that matches:

std::vector<std::regex>> patterns = Get();
for (auto pattern: patterns){
  if (std::regex_match("file.txt",pattern)){
    std::cout << "matched on pattern: " << /* ? pattern ? */ << '\n';
  }
}

std::cout will not work on std::regex.

There doesn't seem to be any methods to get the string representation.

Are we expected to carry around a string separately, or am I missing something in the docs?

Firestone answered 13/11, 2016 at 4:18 Comment(1)
Note that std::regex itself doesn't store the original pattern string, so you need to keep it separately if you want to print it.Glassine
B
8

There doesn't seem to be any methods to get the string representation.

Correct. It is not even specified that the std::regex even saves your expression in the form you gave it, which might be the case if the implementation decides to use some more optimized format.

Bondholder answered 13/11, 2016 at 4:28 Comment(2)
Rats. Seems pretty inconvenient to me, but I guess its not something everyone wants to pay for. I'll make a wrapper type...Firestone
True, especially since boost::regex can be printed.Eucaine

© 2022 - 2024 — McMap. All rights reserved.