Brian Overland, author of C++ for the Impatient , speeds through the basics of regular expression grammar as groundwork for explaining how C++11 regular expressions work.

Read C++ for the Impatient and more than 24,000 other books and videos on Safari Books Online. Start a free trial today.





It's not uncommon to use C++ for text processing; for example, reading a file containing HTML code and writing another file containing the same code in a different HTML format. Could you do that by reading and analyzing one character at a time? Of course. But such tasks can require a lot of work. The new C++11 specification adds the capabilities of regular expressions (regex) to the Standard library, which can make your life easier.

Simply put, a regular expression is a text pattern. It's a boon to text processing, though, enabling you to do a great deal with just a few lines of C++ code. A regular expression grammar is a language unto itself—but a language that's relatively simple and easily learned. Utilizing this grammar, you specify patterns for matching and (optionally) replacing. Then, at runtime, the program builds a regular-expression state machine that does most of the work for you.

You don't really need to know how it works. In fact, you only need to know a few things:

The regular expression grammar used by the C++11 regex library functions

library functions The relevant C++11 functions and how to call them

The first part of this article focuses on the default regex grammar used in C++11: the ECMAScript grammar. You'll generally want to use ECMAScript, because it provides powerful capabilities while being easy to use. For simplicity, I'll focus on this grammar.

Elementary Range Specification

One of the simplest things to do with regular expression grammar is specify a range. For example, you can specify a range matching a single lowercase letter in English:

[a-z]

This regular expression matches exactly one such character. Alternatively, you can specify a range that matches a single lowercase letter, uppercase letter, or digit:

[a-zA-Z0-9]

If this is your first look at a regular expression, you might well ask: How exactly are the different characters used here? The first thing to understand is that the characters a, z, A, Z, 0, and 9 are intended literally; they mean what they are. For example, suppose you used the following regular expression (which is perfectly legal, by the way):

cat2

This expression would match an exact occurrence of cat2 and nothing else.

The brackets ( [ ] ) have a special meaning. Like most special characters, they always have this special meaning unless they're "escaped" by a backslash ( \ ). Let's say you wanted to match a character that can be either an open bracket or a digit. You'd use this regular expression:

[\[0-9]

The backslash ( \ ) causes the second occurrence of the open bracket ( [ ) to lose its special meaning.

But remember that we're dealing with the C++ programming language. The regular expression engine needs to be fed a single backslash in this case, but C++ string notation also uses the backslash as an escape character. Confused yet? The upshot is that (unless you're working with raw literals), it's necessary to use two backslashes in the C++ code itself. This is one of the most important things to understand in using C++ regular expressions. In a program, the string would be coded as follows:

char regex_str[] = "[\\[0-9]";

Specifying Repeated Patterns

Let's return to the initial example: matching a lowercase letter. The following pattern represents a single occurrence of a lowercase letter:

[a-z]

Typically we'd want to match a series of such characters. To do that, the range is followed by an asterisk ( * , meaning "zero or more") or a plus sign ( + , meaning "one or more"). Appending a plus sign—another special character, by the way—says, "Match an occurrence of one or more":

[a-z]+

Already we've come to a point of confusion in the documentation of most regular expressions. You might reasonably think that the plus sign means "Match one or more of the preceding expressions in addition to matching what the expression [a-z] does, which is to match one lowercase letter." Logically, then, you might think that the overall expression [a-z]+ matches two or more letters. But that's not how it works. The plus sign isn't grammatically separate from the expression it follows; rather, it's an expression modifier, changing the meaning of the expression to which it applies. It doesn't mean, "Match the expression one or more times in addition to matching it once."

Therefore, the overall expression [a-z]+ matches any of the following examples:

a x ab cat aardvark

But it doesn't match an empty string. The following expression matches an empty string—as well as longer strings—because the asterisk ( * ) means, "Match the preceding expression zero or more times":

[a-z]*

At this point, you might wonder what gets modified. The answer is that the plus sign and asterisk operators apply to the character immediately preceding, if that would be grammatically sensible, but they can also apply to an immediately preceding range or a group.

Unsurprisingly, parentheses are used to specify a group. Consider the following expression:

Abc+

This expression matches any of the following target strings:

Abc Abcc Abccc

Now consider this expression:

(Abc)+

Enclosed in parentheses, Abc is a group, so this regular expression matches any of the following target strings:

Abc AbcAbc AbcAbcAbc

Before we leave this subject, let's consider another question. Just how many characters are actually matched? The general answer is that, for the most part, the regular expression engine matches as many characters as it can. But consider this innocent-looking expression:

c[a-z]*t

This expression says, "Match the letter c, and then match any number of lowercase letters, and then finally match t." Does this expression match the word cat? Yes, but there's an issue. Once a character is matched, it's not matched again. The letter c, for example, is matched just once. The regex engine then matches as many other lowercase letters as it can. If we take this rule as an absolute, it would match the word at, wouldn't it? But the letter t, already being matched, can't be matched again. The regex engine would then try to match t again—and fail.

As you might suppose, this isn't really how it works. These are the general rules:

The regular expression engine is flexible. It will attempt to match the complete pattern as often as it can, even if this means that certain sub-expressions (in this example, [a-z]* ) actually match fewer characters than possible.

) actually match fewer characters than possible. Otherwise, the regular expression engine will match as many characters in the target string as it can.

The important thing to remember is that an expression such as c[a-z]*t will do exactly what you want. It will match cat, catapult, cut, and clot, among other strings.

Incidentally, if you want the pattern to stop at the first letter t, use this:

c[a-su-z]*t

A Practical Example: MS-DOS File Names

Now we know almost enough to consider a practical example: finding all the file names that appear in a text file. In the Windows and Mac OS X operating systems, file names are flexible, so let's limit ourselves to something close to MS-DOS file names. Let's look for patterns of text that contain the following items, in the order shown:

Match an underscore ( _ ) or an uppercase or lowercase letter. Match any number of underscore, letter, or digit characters. Match a literal dot ( . ). Again, match any number of underscore, letter, or digit characters.

Before formulating the necessary regular expression, we need one more piece of information: how to specify a dot (.), also known as a period or full stop. The dot has a special meaning to regular expression grammar. Therefore, to specify a literal dot, it must be "escaped":

\.

But remember that in a standard C++ string, the backslash also is an escape character; therefore it must be applied twice in C++ code:

string s = "\\."; // Pattern to match a dot (.)

By the way, the dot matches any single character other than a newline (return). So the following regular expression, which may be the most general of all, matches any number of characters, whether printable or whitespace:

.*

It may seem like there are quite a few special characters and therefore a lot of things you need to remember to "escape" (that is, precede with a backslash if you want to represent their literal value). Actually, there aren't many. Here's the set you need to remember:

[ ] ( ) \ . * + ^ ? | { } $

These are mostly the punctuation characters on the top row of your keyboard, other than @ , # , and & .

The hyphen or minus sign ( - ) is a special case. It helps to specify a range, but only if it appears within brackets ( [ ] ), and between two other characters within the range. Otherwise, the minus sign is a literal character and doesn't need to be escaped. By the way, most special characters lose their special meaning inside brackets, except for the brackets themselves. Therefore, you can specify a character that's either a plus or minus sign this way:

[+-]

Now, back to the problem of specifying a file name in MS-DOS style. The regular expression needed is as follows:

[a-zA-Z_][a-zA-Z_0-9]*\.[a-zA-Z0-9]+

To specify this text in a C++ literal string, remember that the backslash must be doubled:

char regex_str[] = "[a-zA-Z_][a-zA-Z_0-9]*\\.[a-zA-Z0-9]+";

Here's the translation: "Match a letter or an underscore. Then match zero or more characters, in which each may be a digit, a letter, or an underscore. Then match a literal dot (.). Finally, match one or more characters, in which each may be a digit or a letter."

If you want to impose the really old MS-DOS convention that permits file extensions of one to three characters, use the {n, m} syntax, which controls how many times the pattern immediately preceding will be repeated:

char regex_str[] = "[a-zA-Z_][a-zA-Z_0-9]*\\.[a-zA-Z0-9]{1,3}";

Using the C++11 regex_search Function

If you already understood the basics of regular expression grammar and waited through the preceding discussion to understand how the C++11 functions work, thank you for your patience. (Or, if you skipped ahead and found the right section, congratulations!)

The first step in using a regular expression in C++ code is to create a regular expression object. Such an object is a rarity in the world of C++: It's compiled at runtime. As a result, regular expressions in C++ are very flexible. You can put strings together dynamically to create entirely new regular expressions at runtime. You can also let the user specify regular expressions.

However, because compiling a regular expression at runtime incurs a performance cost, you should limit your creation of regular expression objects, reusing them as needed. Another problem: Most regular-expression errors aren't detected until runtime, at which point an exception is thrown, so you may need to use exception handling.

Before creating a regular expression object, you need to include some declarations. All class names in the regular expression library are part of the std namespace:

#include <regex> using namespace std;

Then you can create a regular expression object from a C-string ( const char * type) or the STL string class. For example:

string regex_str = "[a-zA-Z_][a-zA-Z_0-9]*\\.[a-zA-Z0-9]+"; regex reg1(regex_str);

You can also specify the regex object more directly:

regex reg1("[a-zA-Z_][a-zA-Z_0-9]*\\.[a-zA-Z0-9]+");

The regex constructor also supports an optional flags field. The most useful of these by far is the regex_constants::icase flag, which causes case to be ignored; in other words, uppercase and lowercase letters are treated interchangeably. By setting this flag, we can write a more succinct pattern string:

string regex_str = "[a-z_][a-z_0-9]*\\.[a-z0-9]+"; regex reg1(regex_str, regex_constants::icase);

NOTE When the statement that creates reg1 is executed, the program launches internal routines at runtime that compile the specified pattern (in this case, according to the flag setting). Therefore, if reg1 is referenced inside a function that you've called multiple times, you should probably make reg1 a global variable or static local, if that's feasible. Otherwise, execution times will be affected.

Now that we have a regex object, we can pass it to some useful C++ functions, such as regex_search . This function returns true if the target string contains one or more instances of the pattern specified in the regular expression object ( reg1 in this case). For example, the following expression would return true ( 1 ) because it finds the substring "readme.txt" within the target string "Print readme.txt" and because "readme.txt" matches the pattern specified in reg1 :

regex_search("Print readme.txt", reg1)

Now consider a more practical application. Let's say you've opened a text file represented by the object txt_fil . You could search for occurrences of file names throughout the text file in this way:

string s; int lineno = 0; while(!txt_fil.eof()) { ++lineno; getline(txt_fil, s); if (regex_search(s, reg1)) { cout << "File name found @ line "; cout << lineno << endl; } }

Iterative Searching (Search All)

As useful as the preceding code fragment is, you'd probably want your application to do more. The regex_search function returns true when it finds the first substring that matches the regular expression pattern. But more often, you'd want to find the occurrence of every substring—not just the first—that matches the pattern.

The regex_iterator class makes writing such code easy. Note that there are at least two such classes (more, if you consider wide character strings):

regex_iterator iterates through a C-string (type const char * ).

iterates through a (type ). sregex_iterator iterates through an object of the STL string class. (Notice that this function name begins with an s, unlike the other function name!)

The STL string class offers many advantages over the old C-string type, so I'll stick with sregex_iterator . Here's how you prepare an sregex_iterator object for use. In this example, we'll use a string object called str and initialize it:

string str = "File names are readme.txt and my.cmd."; sregex_iterator it(str.begin(), str.end(), reg1); sregex_iterator it_end;

NOTE Throughout the examples in this section, remember that reg1 is a regular expression object. The first half of this article described how to create this object.

Here the sregex_iterator class is used to create iterators, a central concept throughout most of the STL (but might be new to you). Basically, an iterator has many features in common with a pointer, but is more sophisticated. You can increment an iterator and dereference it, just like a pointer. You can also compare it to an off-the-edge ending condition.

The following statement creates an iterator that finds substrings from the beginning of the target string to the end of that string:

sregex_iterator it(str.begin(), str.end(), reg1);

As soon as it's created, the iterator ( it ) points to the first substring found (if any), applying the regex pattern in reg1 .

The first substring can be produced by dereferencing the iterator ( *it ). You can then advance to the next substring by incrementing the iterator ( ++it ). We'll apply both these operations in the while statement to follow.

What's unique about sregex_iterator and regex_iterator is that declaring such an iterator without initializing it automatically creates an ending condition. We'll test the iterator against this:

sregex_iterator it_end;

The following code does what you want: Find and print every substring that matches the pattern in the regex object reg1 :

while(it != it_end) { cout << *it << endl; ++it; }

This while statement says: "Compare the current substring found to the iterator's own 'end' condition ( it_end ); if the iterator is at the end, we're done. If the iterator is not equal to its 'end' condition, there is still good data. In that case, print the substring found by dereferencing it ( *it ) and then advance to the next substring ( ++it )."

Now we'll get a printout of every substring. Given the value of the target string shown earlier, the output will be as follows:

readme.txt my.cmd

Summary

Given just the tools introduced in this article, you can do a great deal with regular expressions. For example, you can combine the last two major examples to find and print all the DOS-style file names in a text file, perhaps reporting line numbers. (I leave that exercise for the reader.)

But you can do much more with regular expressions. I haven't begun to discuss the powerful search-and-replace capabilities; that will be the subject of a future article. In the meantime, you can get started using the regular expression library as a powerful way to search string data and text files.