Chapter 7. Regular Expressions

Perl has strong support for regular expressions, or regexes for short. This mini-language within Perl is a tight and powerful way to describe a family of strings that can match a pattern. It’s one of the features that has made Perl so popular.

Today many languages have some sort of access to these powerful tools (perhaps as something called “Perl-Compatible Regular Expressions,” or PCRE), but Perl is still out in front of most them in its power and expressivity.

In the next three chapters, we will show you most of the regex features that you’ll use in most programs. In this chapter, we’ll show you the basics of the regular expression syntax. In Chapter 8, we show you the match operator and more sophisticated ways of employing patterns. Finally, in Chapter 9, we show you ways to use patterns to modify text.

Regexes will probably become one of your favorite parts of the language, at least for a while. But, since regular expressions are tight and compact, they may also frustrate you to no end until you get used to them. That’s normal. As you go through these chapters, try the examples as you read them. The more complex patterns build on what you’ve read earlier.

Sequences

Perl’s regular expressions either match a string or they don’t. There is no such thing as a partial match. And, Perl doesn’t look for a best match. Instead, it matches the leftmost, longest substring that satisfies the pattern.

Note

Some regular expression engines in other languages work differently, ...

Get Learning Perl, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.