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

A final example

As a final example, we present in this section a function which, when given a Regex and a target string, displays all the matching substrings in the target, and for each matching substring, displays the substrings matched by each of the subexpressions in the pattern. Here it is:

     void
     show_all_matches(const Regex &r, const char *target) {
         Regexiter i(r, target);
         Subex subs;
         String mss;
         Substrinfo ss;
         while (ss = i.next(subs, mss)) {
             cout << "pattern matches substring \ " << mss;
             cout << "\ " at " << ss.i << endl;
             show_subs(r, subs);
             cout << endl;
         }
     }
   

// A match on r just produced subs. // Display the info in subs. void show_subs(const Regex &r, const Subex &subs) { for (int i = 1; i <= Regex::max_num_subexes; i++) { String s; Substrinfo ss = subs(i, s); if (ss) { String subex; r.subex(i, subex); cout << "subexpr " << subex; cout << " matched target substring \ "; cout << s << "\ " at " << ss.i << endl; } } }

If we call this function with the following arguments:

       Regex r("(foo)((bar)*)|(baz)");
       show_all_matches(r, "foobarbazfoobaz");

then the resulting output is as follows:

     pattern matches substring "foobar" at 0
     subexpr (foo) matched target substring "foo" at 0
     subexpr ((bar)*) matched target substring "bar" at 3
     subexpr (bar) matched target substring "bar" at 3
   

pattern matches substring "baz" at 6 subexpr (baz) matched target substring "baz" at 6

pattern matches substring "foo" at 9 subexpr (foo) matched target substring "foo" at 9 subexpr ((bar)*) matched target substring " at 12

pattern matches substring "baz" at 12 subexpr (baz) matched target substring "baz" at 12

Acknowledgements Special thanks to Glenn Fowler for having implemented the regular expression compilation and matching routines. Special thanks also to John Isner, Rob Murray, and Jonathan Shopiro for their insights into the design of the library.


Previous topic: Regex iteration

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