|
|
Regex r1("(foo"); // invalid: unmatched ( Regex r2("*"); // invalid: missing operand for * Regex r3("\ "); // invalid: trailing \ is invalid
The validity of a regular expression can be checked by a simple if-test.
Regex r("(foo"); if (!r) cerr << "invalid: " << r.the_error() << endl;
This prints out ``unmatched (''.
An invalid Regex does not match anything:
Regex r("(foo"); r.match("foo"); // false
Invalid Regexes will normally result from an attempt to construct a Regex from a pattern supplied as input to the program. (Presumably, patterns constructed by the program itself should be correct.)
cout << "Give me a pattern, please: "; String s; cin >> s; Regex r(s); if (!r) { cerr << "invalid: " << r.the_error() << endl; // ...
In this situation, the programmer will probably want to loop until the user supplies a valid pattern.
cout << "Give me a pattern, please: "; String s; cin >> s; Regex r(s); while (!r) { cerr << "invalid: " << r.the_error() << endl; cerr << "Please give me a valid pattern: "; cin >> s; r.assign(s); }
In the above, the statement
r.assign(s);
is equivalent to, but faster than, the assignment
r = Regex(s);