Anchors


  • \A matches the beginning of the string
  • \Z matches the end of the string
  • ^ matches the beginning of the row (see also re.MULTILINE)
  • $ matches the end of the row but will accept a trailing newline (see also re.MULTILINE)


examples/regex/anchors.py

import re

lines = [
    "text with cat in the middle",
    "cat with dog",
    "dog with cat",
]

for line in lines:
    if re.search(r'cat', line):
        print(line)


print("---")
for line in lines:
    if re.search(r'^cat', line):
        print(line)

print("---")
for line in lines:
    if re.search(r'\Acat', line):
        print(line)

print("---")
for line in lines:
    if re.search(r'cat$', line):
        print(line)

print("---")
for line in lines:
    if re.search(r'cat\Z', line):
        print(line)
text with cat in the middle
cat with dog
dog with cat
---
cat with dog
---
cat with dog
---
dog with cat
---
dog with cat