Regex

Short for regular expression, a regex is a string of text that enables a user to create pattern matching and locate and manage text. Perl is a great example of a programming language that utilizes regular expressions. Below are a few examples of regular expressions and pattern matching in Perl. Many of these examples are similar or the same to other programming languages and programs that support regular expressions.

$data =~ s/bad data/good data/i;

The above example replaces any "bad data" with "good data" using an insensitive case match. So if the $data variable was "This is bad data" it would become "This is good data".

$data =~ s/a/A/i;

This example replaces any lowercase a with an uppercase A. So if $data was "example" it would become "exAmple".

$data =~ s/[a-z]/*/;

The above replaces any lowercase letter, a through z, with an asterisk. So if $data was "example" it would become "*******".

$data =~ s/e$/es/;

This example uses the $ character, which tells the regular expression to match the text before it at the end of the string. So if $data was "example" it would become "examples".

$data =~ s/\./!/;

In the above example we are replacing a period with an exclamation mark. Because the period is a metacharacter if you were to just enter the period in without the \ or escape it would be treated as any character. In this example if $data was "example." it would become "example!", however, if you didn't have the escape it would replace every character and become "!!!!!!!!"

$data =~ s/^e/E/;

Finally, in this above example the carrot ( ^ ) tells the regular expression to match anything at the beginning of the line. In this example, this would match any lowercase e at the beginning of the line and replace it with a capital E. Therefore if $data was "example" it would become "Example".

Users who are interested in regular expressions in software programs, such as grep, or in their programming language of choice, should definitely check out the O'Reilly book "Mastering Regular Expressions."

Also see: Escape sequence, Expression, Glob, Meta-character, Programming definitions, Tilde, Wildcard