9. Anchors
Anchors match a position, not a character:
^matches only at the start of the string.$matches only at the end of the string, just before a final newline if there is one.
Without an anchor, re.search() finds the pattern anywhere. With ^ the pattern must start at index 0; with $ it must end at the last index. The third example returns None because the string does not start with hello.
re.fullmatch(pattern, string, flags=0) is a stricter check: the pattern must match the entire string, from the first character to the last. It returns a match object or None.
^and$do not consume characters, so they never appear in the result.- Inside a character set,
^means negation instead; that was the previous lesson. re.match()anchors only at the start, whilere.search()has no anchor unless you write one.
Coming from JavaScript? ^ and $ behave the same. re.fullmatch has no direct JS method; the equivalent is a regex wrapped with ^...$ plus test(), or checking that the match length equals the string length.
Anchor at the start
^ makes the pattern start at the first character. Search for r"^hello" in "hello world" and print the matched text.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Anchor at the end
$ makes the pattern end at the last character. Search for r"world$" in "hello world" and print the matched text.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
The anchor fails in the middle
Search for r"^hello" in "say hello". hello appears, but not at the start, so re.search() returns None. Print the result directly.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Require a full match
re.fullmatch() only succeeds when the pattern matches the whole string. Use the pattern r"[a-z]{3}[0-9]{3}" on "abc123". If re.fullmatch() finds a match, print valid; otherwise print invalid.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Validate the end of an address
Combine an escaped dot with the end anchor. Search for r"@gmail\.com$" in "ada@gmail.com". If it matches, print gmail; otherwise print other.
Print exactly:
Create a free account to save your progress and unlock chapter 2.