Pangi
Pangi

Reputation: 99

Debug regex mismatch

I want to know if there is a way to have some sort of diagnostics regarding a mismatch when using std::regex to match a std::string.

std::string to_match = "abc123abc123";
std::regex re("(abc)(123)(sss)123");
bool b = std::regex_match(to_match, re);

I want to know something about the mismatch above, for example that the mismatch occurred at character 7 in to_match.

Upvotes: 1

Views: 740

Answers (1)

Andreas DM
Andreas DM

Reputation: 10998

I want to know something about the mismatch above, for example that the mismatch occurred at character 7 in to_match.

There is no utility that lets you see the mismatch of the regular expression in the standard library.
The expression matches or it does not, simple as that.


If you absolutely want to find where it mismatches (for simple expressions), I suppose you could go the bruteforce route

  • Does (abc)(123)(sss)123 match?
  • Does (abc)(123)(sss)12 match?
  • Does (abc)(123)(sss)1 match?
  • Does (abc)(123)(sss) match?

Etc. But that is only one way, and it doesn't account for taking away subexpressions like

(abc)(123)(sss)123
     ^^^^^
  taking away that

And you would need to handle the parenthesis:

Does "(abc)(123)(sss" match?
                    ^
               ops, missing parenthesis. This will throw an exception.

This might work for simple expressions like the above if you handle the the expressions correctly, very error prone.

But imagine when the expressions become more complex like quantifiers, decisions, lookaround etc. Then the task will become much much more difficult.


I agree with the comments and suggest using an external regex tool for testing your regular expressions.

Upvotes: 2

Related Questions