天天看点

The GRETA Regular Expression Template Archive

     The regular expression template library contains objects and functions that make it possible to perform pattern matching and substitution on strings in C++.  They are:

        rpattern: the pattern to use during the search.

        match_results/subst_results: container for the results of a match/substitution.

    To perform a search or replace operation, you will typically first initialize an rpattern object by giving it a string representing the pattern against which to match.  You will then call a method on the rpattern object (match() or substitute(), for instance), passing it a string to match against and a match_results objects to receive the results of the match.  If the match()/substitute() fails, the method returns false.  If it succeeds, it returns true, and the match_results object stores the resulting array of backreferences internally.  (Here, the term backreference has the same meaning as it does in Perl.  Backreferences provide extra information about what parts of the pattern matched which parts of the string.)  There are methods on the match_results object to make the backreference information available.  For example:

#include <iostream>

#include <string>

#include “regexpr2.h”

using namespace std;

using namespace regex;

int main() {

    match_results results;

    string str( “The book cost $12.34” );

    rpattern pat( “//$(//d+)(//.(//d//d))?” ); 

    // Match a dollar sign followed by one or more digits,

    // optionally followed by a period and two more digits.

    // The double-escapes are necessary to satisfy the compiler.

    match_results::backref_type br = pat.match( str, results );

    if( br.matched ) {

        cout << “match success!” << endl;

        cout << “price: ” << br << endl;

    } else {

        cout << “match failed!” << endl;

    }

    return 0;

}

    The above program would print out the following:

         match success!

         price: $12.34

    The following sections discuss the rpattern object in detail and how to customize your searches to be faster and more efficient.

     Note: all declarations in the header file (regexpr2.h) are contained in the regex namespace.  To use any of the objects, methods or enumerations described in this document, you must prepend all declarations with “regex::” or you must have the “using namespace regex;” directive somewhere within the enclosing scope of your declarations.  For simplicity, I’ve left off the “regex::” prefixes in the rest of my code snippets.

继续阅读