2

I'm currently validating if a string is a valid regex string by using a try, catch. I'd like to instead preferably do this without a try, catch, and some sort of bool returning function.

Are there any options? (minimal version using the std)

Example using try, catch:

std::wstring regex;
try {
        wregex re(regex);
    }
    catch (const std::regex_error& ) {

}

5
  • Write a function that implements the regex logic and returns false if an exception was thrown and true otherwise Commented May 3, 2020 at 0:15
  • @ThomasSablik I'm going to assume I haven't made it clear enough, but I want to remove exceptions completely. Commented May 3, 2020 at 0:20
  • 1
    If you want to use only standard library I think there aren't any options. Do you want to use a third party library? Commented May 3, 2020 at 0:29
  • @ThomasSablik I'll see if I can wait for a std example (if there are any). I'd like to keep things minimal thus preferably no 3rd party libs Commented May 3, 2020 at 1:11
  • @dk123 you need to edit your question to add this information. Comments are for requesting clarifications. Everything that is pertinent to the question needs to be in the body of the question Commented May 3, 2020 at 2:00

2 Answers 2

4

Write a function that implements the regex logic and returns false if an exception was thrown and true otherwise

bool isValid(const std::wstring &regex) {
    try {
        wregex re(regex);
    }
    catch (const std::regex_error& ) {
        return false;
    }
    return true;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could use boost::regex which can be switched into a non-throwing mode. For example:

#include <boost/regex.hpp>
#include <iostream>

int main() {
  const boost::regex valid_re("\\d+", boost::regex_constants::no_except);
  if (valid_re.status() == 0) {
    std::cout << std::boolalpha << regex_match("123", valid_re) << "\n";
  } else {
    std::cout << "Invalid regex\n";
  }

  const boost::regex invalid_re("[", boost::regex_constants::no_except);
  if (invalid_re.status() == 0) {
    std::cout << std::boolalpha << regex_match("123", invalid_re) << "\n";
  } else {
    std::cout << "Invalid regex\n";
  }
}

Output:

true
Invalid regex

Make sure you are calling regex_match() only after checking the status(). Calling regex_match() will throw an exception if the regular expression is invalid!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.