What are regular expressions in Perl?

In Perl, Regular expressions are user-determined strings that we can use for pattern-matching in a text. We use these patterns to determine if the ‘target’ string has the characteristics defined in the pattern.

Operators

The following are the three operators used for pattern matching in Perl:

  • m//: Match Regular Expression
    We use this operator to find matches of regular expressions in the target text. The following table shows the modifiers associated with this operator:

Modifier

Description

i

This modifier makes the pattern matching case-sensitive.

o

This modifier makes sure that the pattern is matched once at most.

s

This modifier allows using "." to match a newline character.

x

This modifier allows the use of whitespace in the pattern.

g

This modifier makes sure all matches globally are found.

cg

This modifier lets the search continue even if there is no global match

  • s///: Subsitute Regular Expression
    We use this operator to find matches of regular expressions in the target text, and then replace them with the given piece of text. The following table shows the modifiers associated with this operator:

Modifier

Description

i

This modifier makes the pattern matching case-sensitive.

o

This modifier makes sure that the pattern is only matched at most once.

s

This modifier allows using "." to match a newline character.

x

This modifier allows the use of whitespace in the pattern.

g

This modifier makes sure all matches globally are found.

e

This modifier evaluates the replacement text as Perl code and uses the evaluated result as the replacement text.

  • tr///: Transliterate Regular Expression
    This operator is similar to the substitute operator – it is used to find matches of characters (instead of regular expressions) in the target text, and replace them with the given characters.

Modifier

Description

c

This modifier complements the searchlist.

d

This modifier is used to delete characters that were found but not replaced

s

This modifier is used to squash duplicate replaced characters

Code

The following coded examples show the various uses of regular expressions.

# match regular expression
$str = "This is an Edpresso shot.";
if ($str =~ /shot/) { #searches for a match
print "Found a match.\n";
} else {
print "No match found.\n";
}
# substitute regular expression
$str =~ s/Edpresso/Educative/; # substitute Edpresso with Educative
print $str, "\n";
# transliterate regular expression
$str =~ tr/a/o/; # modify all "a" characters to "o"
print $str, "\n";

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved