Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

20.3. Constructing a RegEx String

The previous two sections provided an introduction to regular-expression patterns. The next several sections summarize the syntax rules, beginning with the syntax for matching individual characters.

This chapter adopts the default grammar used by the C++11 regular-expression library, which is a modified ECMAScript grammar. Although it’s possible to use variations, the C++11 default is more versatile and expressive than the alternative grammars.

20.3.1. Matching Characters

The following special expressions match an individual character belonging to a group, such as letters or digits. This section also describes special conditions such as beginning-of-line or word boundary.

In the following list, a range may be a list of characters (not separated by spaces or commas, which themselves are characters). A range may optionally use a dash (minus sign) to indicate a run beginning with one character, up to and including another. Characters are ordered according to their underlying numeric (ASCII) value. For example, “[a-z]” matches all lowercase letters.

  • b-tri.jpg .

    Matches any one character other than a newline. For example, the following pattern string matches almost any single character:

    "."

  • b-tri.jpg [range]

    Matches any one character in the specified range. For example, the following pattern string matches any single letter in the range “a” to “m”. It also matches “z”.

    "[a-mz]"

    Most characters lose their special meaning inside the brackets. The minus sign gains special meaning to indicate a run of characters as in the example just shown, but only if it appears between two other characters inside the range. The following expression matches any one of the characters “+”, “*”, “/”, or “-”. None of these need to be escaped.

    "[+*/-]"
  • b-tri.jpg [^range]

    Matches any character not in the specified range. For example, the following pattern string matches any single character other than “a”, “b”, or “c”:

    "[^abc]"
  • b-tri.jpg \n

    Matches a newline. When using this in a C++ literal string meant to be part of a regular-expression pattern-matching string (as opposed to an actual embedded newline), remember that two backslashes must be used. For example:

    "\\n"
  • b-tri.jpg \t

    Matches a tab character.

  • b-tri.jpg \f

    Matches a form feed.

  • b-tri.jpg \r

    Matches a carriage return.

  • b-tri.jpg \v

    Matches a vertical tab.

  • b-tri.jpg \xhh

    Matches a character specified as a hexadecimal code. For example:

    "\\xf3"
  • b-tri.jpg \uhhhh

    Matches a Unicode character specified as a hexadecimal code. For example:

    "\\u02f3"
  • b-tri.jpg \d

    Matches any digit character. This is equivalent to:

    [0-9]
  • b-tri.jpg \D

    Matches any character other than a digit. This is equivalent to:

    [^0-9]
  • b-tri.jpg \s

    Matches any whitespace character.

  • b-tri.jpg \S

    Matches any character other than a whitespace character.

  • b-tri.jpg \w

    Matches any digit, letter, or underscore.

  • b-tri.jpg \W

    Matches any character other than a digit, letter, or underscore.

  • b-tri.jpg \b

    Matches a word boundary. A word must begin or end at this position, or there is no match. Words are made up of alphanumeric characters and are delimited by whitespaces and punctuation. For example, the following string matches any word beginning with “c” and ending with “t”, such as “cat” or “containment”. It does not match “caution”.

    "\\bc[a-zA-Z]*t\\b"
  • b-tri.jpg \B

    Not a word boundary. For example, the following pattern matches a portion of a word beginning with “a.” It will match “at” embedded in “cat”, but it will not match “at” if it occurs as a stand-alone word.

    "\\Ba[a-zA-Z]*"
  • b-tri.jpg ^

    Beginning of line: The next character is matched only if it is the first character in the text to be examined or occurs just after a newline.

    "^Barney"
  • b-tri.jpg $

    End of line: The previous character matched (if any) must be the last character in the line of text.

20.3.2. Pattern Modifiers

Regular-expression pattern matching becomes more interesting when you modify a pattern to indicate possible repetitions. This feature, as much as anything else, makes the regular-expression technology a powerful and versatile tool for searching and replacing text.

In the following list, expr is an expression. For example, in the string “[0-9]+”, “[0-9]” is an expression and the + operator modifies its meaning.

An operator associates with the character closest to it, except where brackets or parentheses are used, in which case the operator refers to the whole range or group that precedes it.

  • b-tri.jpg expr*

    Matches zero or more instances of expr. For example, the following string matches an empty string or a digit string:

    "[0-9]*"
  • b-tri.jpg expr+

    Matches one or more instances of expr. For example, the following string matches a digit string of length one or greater.

    "[0-9]+"
  • b-tri.jpg expr?

    Matches either one or zero instances of expr. The expr thereby becomes an optional item that can appear at most once. For example, the following string matches a minus sign or an empty string.

    "-?"
  • b-tri.jpg expr1|expr2

    Matches expr1 or expr2, but not both. For example, the following regular-expression string matches “aa” or “bb” but not “aabb”.

    "(aa)|(bb)"

    This expression can be made optional by placing it in a larger group and then using the ? operator. In that case, “aa” may appear, “bb” may appear, or they may both be omitted.

    "((aa)|(bb))?"
  • b-tri.jpg expr{n}

    Matches exactly n instances of expr. For example, the following pattern string matches a target string containing exactly ten copies of capital “A”.

    "A{10}"
  • b-tri.jpg expr{n,}

    Matches n or more instances of expr. For example, the following pattern string matches a target string consisting of three or more digits.

    "[0-9]{3,}"
  • b-tri.jpg expr{n,m}

    Matches at least n, but no more than m, instances of expr. For example, the following pattern string matches a digit string no more than seven digits long.

    "[0-9]{1,7}"
  • b-tri.jpg (expr)

    Forms a group. expr is considered as a unit when modified by other special characters, as in (expr)+, (expr)*, and so on. For example, the following pattern string matches “AbcAbcAbc” in the target string:

    "(Abc){3}"

    Another important effect of parentheses is that they cause the expression inside to be “tagged,” as explained in the next section.

20.3.3. Recurring Groups

Much of the power of regular expressions comes from the ability to look for repetitions of a group. The syntax:

\n

refers to a previously tagged group. The expressions \1, \2, and \3 refer to the first three groups. Remember that C++ string literals use the backslash as an escape character, so the expressions “\1”, “\2”, and “\3” must be rendered as \\1, \\2, and \\3, and so on, in C++ source code (unless you’re using raw string literals).

For example, the following expression—expressed as a string literal—matches aa, bb, and cc:

"(a|b|c)\\1"

This expression first matches a, b, or c. Whatever is matched is tagged. The regex pattern must then immediately match this tagged character again if it is to match the overall expression.

It will therefore match aa and bb, but not ab.

The next example is more practical: It finds a repeated word, in which a single space separates the two words:

"([A-Za-z]+) \\1"

This expression says, “Match a series of one or more letters. Tag the characters in this group. Then match a space. Finally, match an exact recurrence of the tagged characters.” The following strings would therefore be matched:

"the the"
"Monday Monday"
"Rabbit Rabbit"

20.3.4. Character Classes

The C++11 grammar also provides a series of character classes that can be used to help specify a range. For example, the following expression specifies a range consisting of any letter:

[[:alpha:]]

This is equivalent to:

[A-Za-z]

The following expression specifies a range consisting of any letter or punctuation character:

[[:alpha:][:punct:]]

Descriptions of the character classes follow.

  • b-tri.jpg [:alnum:]

    Any letter or digit.

  • b-tri.jpg [:alpha:]

    Any letter.

  • b-tri.jpg [:blank:]

    A space or tab character.

  • b-tri.jpg [:cntrl:]

    Any control character. (These are not printable.)

  • b-tri.jpg [:digit:]

    Any decimal digit.

  • b-tri.jpg [:graph:]

    Any printable character that is not a whitespace.

  • b-tri.jpg [:lower:]

    Any lowercase letter.

  • b-tri.jpg [:print:]

    Any printable character, including whitespaces.

  • b-tri.jpg [:punct:]

    Any punctuation character.

  • b-tri.jpg [:space:]

    A whitespace character, such as a blank space, tab, or newline.

  • b-tri.jpg [:upper:]

    Any uppercase letter.

  • b-tri.jpg [:xdigit:]

    A hexadecimal digit: This includes digits, as well as uppercase and lowercase letters.

  • + Share This
  • 🔖 Save To Your Account

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