How regular expression anchors work in Python?

PythonServer Side ProgrammingProgramming

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
raja
Published on 07-Jan-2018 16:27:01
Advertisements