Home > Articles > Programming > C/C++

Regular Expressions 101: Regex in C++11

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.



Like this article? We recommend

Like this article? We recommend

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
  • 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.
  • 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:

  1. Match an underscore (_) or an uppercase or lowercase letter.
  2. Match any number of underscore, letter, or digit characters.
  3. Match a literal dot (.).
  4. 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);

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 *).
  • 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;

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020