Regular Expressions
Regular expressions (a.k.a. regexes, regexps, or REs) are used by many search programs such as grep and findstr, text-munging programs like sed and awk, and editors like vi and emacs. A regular expression is a way of describing a set of strings without having to list all the strings in your set.[22]
Many other computer languages incorporate regular
expressions (some of them even advertise "Perl5 regular
expressions"!), but none of these languages integrates regular
expressions into the language the way Perl does. Regular expressions
are used several ways in Perl. First and foremost, they're used in
conditionals to determine whether a string matches a particular
pattern, because in a Boolean context they return true and false. So
when you see something that looks like /foo/ in a
conditional, you know you're looking at an ordinary
pattern-matching operator:
if (/Windows 95/) { print "Time to upgrade?\n" }Second, if you can locate patterns within a string, you
can replace them with something else. So when you see something that
looks like s/foo/bar/, you know it's asking Perl to
substitute "bar" for "foo", if possible. We call that the
substitution operator. It also happens to return
true or false depending on whether it succeeded, but usually it's
evaluated for its side effect:
s/Windows/Linux/;
Finally, patterns can specify not only where something
is, but also where it isn't. So the
split operator uses a regular expression to specify where the data isn't. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access