How to match start and end of string with ^ and $ in Perl?
Question
How to match start and end of string with ^ and $ in Perl?
In Perl regular expressions, the anchors ^ and $ are used to match the start and end of a string, respectively. These anchors do not match any actual characters but assert a position in the target string, allowing you to control where your pattern matches.
Understanding ^ and $ anchors
^matches the start of the string (or the start of a line if/mmodifier is used).$matches the end of the string (or the end of a line if/mmodifier is used).
Common use cases include:
- Matching an entire string exactly with a pattern.
- Making sure a substring only appears at the very beginning or end.
- Anchoring patterns to lines in multiline strings via the
/mmodifier.
Example: Matching an entire string
If you want to check if a string equals exactly hello, you combine ^ and $ like this:
#!/usr/bin/perl
use strict;
use warnings;
my $string = "hello";
if ($string =~ /^hello$/) {
print "Matched exactly 'hello'\n";
} else {
print "No match\n";
}
# Testing with a string that contains 'hello' but not exactly equal
my $string2 = "hello world";
if ($string2 =~ /^hello$/) {
print "Matched exactly 'hello'\n";
} else {
print "No match for string2\n";
}
Output:
Matched exactly 'hello'
No match for string2
Key Points About ^ and $
- The
^matches the position before the first character of the string (or line in/mmode). - The
$matches the position after the last character of the string (or line in/mmode). It also matches before a newline at the end unless you use the/smodifier. - Without the
/mmodifier,^and$always match the start and end of the entire string. - With the
/mmodifier,^and$match the start and end of any line (line is a substring separated by newlines). - To match the very end of string and ignore trailing newline, consider using
\zanchor instead of$.
Example with multiline string and /m modifier
my $multiline = "first line\nsecond line\nthird line";
while ($multiline =~ /^(.*)$/mg) {
print "Line matched: '$1'\n";
}
This code will match each line individually because /m tells ^ and $ to consider newlines as line boundaries.
Common Pitfalls
- For matching exact strings, always use both
^and$. Omitting them allows the pattern to match anywhere in the string. - Remember that
$can match just before a trailing newline, so your match may succeed even if extra newline is present at the end. - If you want to strictly match end of string ignoring trailing newlines, use
\zinstead of$(available since Perl 5). - Without
/m,^and$only match the start and end of the whole string, not internal lines.
Mastering ^ and $ anchors is fundamental for precise regex matching in Perl, especially when you want to assert position rather than matching characters directly.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 5ms
Matched exactly 'hello'
No match for string2
(empty)