-2

I want to initialize a std::wregex with a std::wstring, but if I give a std::wstring that do not conform to regular expression syntax(for example, std::wstring(L"*")), the initialization will crash.

std::wstring userRegex;
std::wcout << L"input regex: ";
std::wcin >> userRegex;//for example,userRegex == std::wstring(L"*")
std::wregex pattern = std::wregex(userRegex) //crash

try-catch is not allowed in my code. I want to ensure that any std::wstring input will not cause a crash. If this std::wstring does not follow the syntax rules of regular expressions, my code should inform me and return it in advance.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
key zhao
  • 1
  • 1
  • 1
    Use a third-party regex library? The standard ones are known to not work well anyway. – HolyBlackCat Aug 31 '23 at 03:40
  • Yes there is (if you can initialize your regexes directly, so no extra runtime std::wstring) [compile time regular expression](https://github.com/hanickadot/compile-time-regular-expressions). See [CppCon 2018: Hana Dusíková “Compile Time Regular Expressions”](https://www.youtube.com/watch?v=QM3W36COnE4). – Pepijn Kramer Aug 31 '23 at 03:42
  • @PepijnKramer since OP is talking about validating a regex before instantiating `basic_regex` I don't think they are working with compile-time constant strings. It would be trivial to hand-craft correct ones *once*. – Marco Bonelli Aug 31 '23 at 03:44
  • @MarcoBonelli Fair enough ;) Using exceptions is not always allowed on firmware. – Pepijn Kramer Aug 31 '23 at 04:03
  • 2
    *try-catch is not allowed in my code* -- Then you have much more to be concerned with than `std::wregex`. If there is any usage of `new` or `new[]` in your code or in third-party library code also will have issues, just like`std::vector::at()`, `std::stoi()`, and I could go on and on. – PaulMcKenzie Aug 31 '23 at 04:05

0 Answers0