VOOZH about

URL: https://www.geeksforgeeks.org/perl/perl-anchors-in-regex/

⇱ Perl | Anchors in Regex - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perl | Anchors in Regex

Last Updated : 12 Jul, 2025
Anchors in Perl Regex do not match any character at all. Instead, they match a particular position as before, after, or between the characters. These are used to check not the string but its positional boundaries. Following are the respective anchors in Perl Regex:
'^' '$', '\b', '\A', '\Z', '\z', '\G', '\p{....}', '\P{....}', '[:class:]'
  ^ or \A: It matches the pattern at the beginning of the string.
Syntax: (/^pattern/, /\Apattern/).
Example:
Output:
guardians
gua
  $ or \z: It matches the pattern at the end of the string.
Syntax: (/pattern$/, /pattern\z/).
Example:
Output:
y
galaxy
  \b: It matches at the word boundary of the string from \w to \W. In precise, it either gets a match to beginning or end of the string if it is a word or to a word character or a non-word character.
Syntax: (/\bpattern\b/).
Example:
Output:
-galaxy
guardians-
guardians-of-the-galaxy
  \Z: It matches at the ending of the string or before the newline. '\z' and '\Z' both differ from $ in that they are not affected by the /m "multiline" flag, which allows $ to match at the end of any line.
Output:
one
two
three
four
five
  \G: It matches at the specified position. If a pattern's length is 5 then it starts from the start of the string till 5 positions, if the pattern is valid then it is forced to check the string from 6th position onwards, moves forward in this fashion till pattern not valid or end of the string.
Output:
one: ga one: la one: xy 
two: 11 two: 22 
three: ga three: la three: xy three: 82 three: 22 three: as 
five: 82 five: 22 five: as
  \p{...} and \P{...}: \p{...} matches Unicode character class like IsLower, IsAlpha, etc. whereas \P{….} is the complement of Unicode character class.
Output:
guardians
guardians123
!@#%^&*123
guardians
  [:class:]: POSIX Character Classes like digit, lower, ascii, etc.
Syntax: (/[[:class:]]/)
POSIX character classes are as follows:
alpha, alnum, ascii, blank, cntrl, digit, graph, lower, punct, space, upper, xdigit, word
Output:
guardians
guardians123
123
guardians!@#%^&123
1
guardians
guardians!@#%^& 123
Comment
Article Tags:
Article Tags:

Explore