Anchors
Lesson 12 of 28 in Coddy's RegEx in Python course.
Anchors are special characters in regex that match positions rather than actual characters. The two most common anchors are ^ and $.
<strong>^</strong>: Matches the start of a string.<strong>$lt;/strong>: Matches the end of a string.
import re
text = "Hello, world!"
pattern_start = r"^Hello"
pattern_end = r"world!$"
match_start = re.search(pattern_start, text)
match_end = re.search(pattern_end, text)
if match_start:
print("Start anchor match found:", match_start.group()) # Output: Start anchor match found: Hello
else:
print("No start anchor match found")
if match_end:
print("End anchor match found:", match_end.group()) # Output: End anchor match found: world!
else:
print("No end anchor match found")In the above example, the pattern ^Hello matches "Hello" at the start of the string, and the pattern world!$ matches "world!" at the end of the string
Challenge
EasyWrite a function named find_lines_starting_with that takes a list of strings and a word as input, and returns a list of strings that start with the given word.
Try it yourself
import re
def find_lines_starting_with(lines, word):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction