dk123
dk123

Reputation: 19690

c++ check if string is valid regex string without exception

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& ) {

}

Upvotes: 2

Views: 2771

Answers (2)

Martin Konrad
Martin Konrad

Reputation: 1095

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!

Upvotes: 0

Thomas Sablik
Thomas Sablik

Reputation: 16454

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;
}

Upvotes: 4

Related Questions