# How regular expression anchors work in Python?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Anchors are regex tokens that don't match any characters but that say or assert something about the string or the matching process. Anchors inform us that the engine's current position in the string matches a determined location: for example, the beginning of the string/line, or the end of a string/line.

This type of assertion is useful for  many reasons. First, it lets you specify that you want to match alphabets/digits at the beginning/end of a string/line, but not anywhere else. Second, when you tell the engine that you want to find a pattern at a certain location, it  need not find that pattern at any other locations. This is why  it is recommended to use anchors whenever possible.

^ and $are two examples of anchor tokens in regex. The following code shows the use of anchors ^ and$

import re
s = 'Princess Diana was a beauty icon'
result = re.search(r'^\w+', s)
print result.group()
result2 = re.search(r'\w+\$', s)
print result2.group()

This gives the output

Princess
icon
Updated on 30-Jul-2019 22:30:21