DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
A Portable C++ Regular Expression Facility - Regex(3C++)

Invalid patterns

Not all patterns are valid.

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

Next topic: More on matching
Previous topic: Constructing and matching

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004