# Chapter 32. Regular Expressions (Pattern Matching)

#### Contents:

That's an Expression
Don't Confuse Regular Expressions with Wildcards
Understanding Expressions
Using Metacharacters in Regular Expressions
Regular Expressions: The Anchor Characters ^ and $
Regular Expressions: Matching a Character with a Character Set
Regular Expressions: Match Any Character with . (Dot)
Regular Expressions: Specifying a Range of Characters with [...]
Regular Expressions: Exceptions in a Character Set
Regular Expressions: Repeating Character Sets with *
Regular Expressions: Matching a Specific Number of Sets with \ { and \ }
Regular Expressions: Matching Words with \ < and \ >
Regular Expressions: Remembering Patterns with \ (, \ ), and \1
Regular Expressions: Potential Problems
Extended Regular Expressions
Getting Regular Expressions Right
Just What Does a Regular Expression Match?
Limiting the Extent of a Match
I Never Meta Character I Didn't Like
Valid Metacharacters for Different Unix Programs
Pattern Matching Quick Reference with Examples

## 32.1. That's an Expression

When my young daughter is struggling to understand the meaning of an idiomatic expression, such as, "Someone let the cat out of the bag," before I tell her what it means, I have to tell her that it's an expression, that she's not to interpret it literally. (As a consequence, she also uses "That's just an expression" to qualify her own remarks, especially when she is unsure about what she has just said.)

An expression, even in computer terminology, is not something to be interpreted literally. It is something that needs to be evaluated.

Many Unix programs use a special "regular expression syntax" for specifying what you could think of as "wildcard searches" through files. Regular expressions describe patterns, or sequences of characters, without necessarily specifying the characters literally. You'll also hear this process referred to as " pattern matching."

In this chapter, we depart a bit from the usual "tips and tricks" style of the book to provide an extended tutorial about regular expressions that starts in Section 32.4. We did this because regular expressions are so important to many of the tips and tricks elsewhere in the book, and we wanted to make sure that they are covered thoroughly.

This tutorial article is accompanied by a few snippets of advice (Section 32.16 and Section 32.18) and a few tools that help you see what your expressions are matching (Section 32.17). There's also a quick reference (Section 32.21) for those of you who just need a refresher.

For tips, tricks, and tools that rely on an understanding of regular expression syntax, you have only to look at:

- Chapter 13

- Chapter 17

- Chapter 20

- Chapter 34

- Chapter 41

O'Reilly's Mastering Regular Expressions, by Jeffrey Friedl, is a gold mine of examples and specifics.

--DD and TOR

Copyright © 2003 O'Reilly & Associates. All rights reserved.