7.7. Regex Anchor
^
- start of line (changes meaning withre.MULTILINE
)$
- end of line (changes meaning withre.MULTILINE
)\A
- start of text (doesn't change meaning withre.MULTILINE
)\Z
- end of text (doesn't change meaning withre.MULTILINE
)
7.7.1. SetUp
import re
7.7.2. Start of Line
^
- start of a lineChanges meaning with
re.MULTILINE
Search for a capital letter at the start of a line:
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'^[A-Z]', TEXT)
['O']
Search for a capital letter anywhere in text:
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'[A-Z]', TEXT)
['O', 'S', 'J', 'A', 'M', 'A']
7.7.3. End of Line
$
- end of lineChanges meaning with
re.MULTILINE
Give me last characters in a line:
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'.$', TEXT)
['e']
7.7.4. Start of String
\A
- start of a textDoesn't change meaning with
re.MULTILINE
Search for a capital letter in text at the start of a line:
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'\A[A-Z]', TEXT)
['O']
Note, that the output is identical to Start of a Line ^
. It will differ
when re.MULTILINE
flag is present.
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'^[A-Z]', TEXT)
['O']
7.7.5. End of String
\Z
- end of a textDoesn't change meaning with
re.MULTILINE
Give me last character in a text:
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'.\Z', TEXT)
['e']
Note, that the output is identical to Start of a Line ^
. It will differ
when re.MULTILINE
flag is present.
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'.$', TEXT)
['e']
7.7.6. Multiline
Multiline strings are in fact one line with multiple newline characters (
\n
)re.MULTILINE
text = """First line
Second line
Third line"""
Start and end of the text:
re.findall(r'\A.', text)
['F']
re.findall(r'.\Z', text)
['e']
Start and end of the line (problem):
re.findall(r'^.', text)
['F']
re.findall(r'\A.', text)
['F']
Why this is not working?
text
'First line\nSecond line\nThird line'
Start and end of the line (solution):
re.findall(r'^.', text, flags=re.MULTILINE) ['F', 'S', 'T']
re.findall(r'A.', text, flags=re.MULTILINE) ['F']
7.7.7. Case Study
import re
text = """Apollo 11 was a mission that first landed humans on the Moon. Neil Armstrong
was first person to step onto the moon's surface. Buzz Aldrin joined him 19
minutes later. They spent 2 hours 31 minutes exploring the Sea of Tranquility.
Both astronauts collected lunar material. Neil and Buzz were on the Moon's
surface for 21 hours 36 minutes. Pilot Michael Collins waited for them in the
lunar orbit."""
# %%
re.findall(r'\A.', text)
# ['A']
# %%
re.findall(r'.\Z', text)
# ['.']
import re
text = """Apollo 11 was a mission that first landed humans on the Moon. Neil Armstrong
was first person to step onto the moon's surface. Buzz Aldrin joined him 19
minutes later. They spent 2 hours 31 minutes exploring the Sea of Tranquility.
Both astronauts collected lunar material. Neil and Buzz were on the Moon's
surface for 21 hours 36 minutes. Pilot Michael Collins waited for them in the
lunar orbit."""
# %%
re.findall(r'^.', text)
# ['A']
# %%
re.findall(r'.$', text)
# ['.']
import re
text = """Apollo 11 was a mission that first landed humans on the Moon. Neil Armstrong
was first person to step onto the moon's surface. Buzz Aldrin joined him 19
minutes later. They spent 2 hours 31 minutes exploring the Sea of Tranquility.
Both astronauts collected lunar material. Neil and Buzz were on the Moon's
surface for 21 hours 36 minutes. Pilot Michael Collins waited for them in the
lunar orbit."""
text
"Apollo 11 was a mission that first landed humans on the Moon. Neil Armstrong\nwas first person to step onto the moon's surface. Buzz Aldrin joined him 19\nminutes later. They spent 2 hours 31 minutes exploring the Sea of Tranquility.\nBoth astronauts collected lunar material. Neil and Buzz were on the Moon's\nsurface for 21 hours 36 minutes. Pilot Michael Collins waited for them in the\nlunar orbit."
# %%
re.findall(r'\A.', text, flags=re.MULTILINE)
# ['A']
# %%
re.findall(r'.\Z', text, flags=re.MULTILINE)
# ['.']
# %%
re.findall(r'^.', text, flags=re.MULTILINE)
# ['A', 'w', 'm', 'B', 's', 'l']
# %%
re.findall(r'.$', text, flags=re.MULTILINE)
# ['g', '9', '.', 's', 'e', '.']
7.7.8. Assignments
# %% About
# - Name: RE Syntax Anchor
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Define `result_a: str` with regular expression pattern to find
# character at the beginning of a text
# example: ['A']
# 2. Define `result_b: str` with regular expression pattern to find
# character at the beginning of each line
# example: ['A', 'h', 'p', 'J', 't', 'o', 'T', 'B', 'o', 'f', 'M', 'C']
# 3. Define only regex pattern (str), not re.findall(...)
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result_a: str` z wzorcem wyrażenia regularnego aby wyszukać
# znak na początku tekstu
# przykład: ['A']
# 2. Zdefiniuj `result_b: str` z wzorcem wyrażenia regularnego aby wyszukać
# znak na początku każdej linii
# przykład: ['A', 'h', 'p', 'J', 't', 'o', 'T', 'B', 'o', 'f', 'M', 'C']
# 3. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% References
# [1] Authors: Wikipedia contributors
# Title: Apollo 11
# Publisher: Wikipedia
# Year: 2019
# Retrieved: 2019-12-14
# URL: https://en.wikipedia.org/wiki/Apollo_11
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> result = re.findall(result_a, DATA, flags=re.MULTILINE)
>>> pprint(result, compact=True)
['A']
>>> result = re.findall(result_b, DATA, flags=re.MULTILINE)
>>> pprint(result, compact=True)
['A', 'h', 'p', 'J', 't', 'o', 'T', 'T', '(', '(', 'M', 'C']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import re
# %% Types
result_a: str
result_b: str
# %% Data
DATA = """Apollo 11 was the American spaceflight that first landed
humans on the Moon. Commander (CDR) Neil Armstrong and lunar module
pilot (LMP) Buzz Aldrin landed the Apollo Lunar Module (LM) Eagle on
July 20th, 1969 at 20:17 UTC, and Armstrong became the first person
to step (EVA) onto the Moon's surface (EVA) 6 hours 39 minutes later,
on July 21st, 1969 at 02:56:15 UTC. Aldrin joined him 19 minutes later.
They spent 2 hours 31 minutes exploring the site they had named
Tranquility Base upon landing. Armstrong and Aldrin collected 47.5 pounds
(21.5 kg) of lunar material to bring back to Earth as pilot Michael Collins
(CMP) flew the Command Module (CM) Columbia in lunar orbit, and were on the
Moon's surface for 21 hours 36 minutes before lifting off to rejoin
Columbia."""
# %% Result
result_a = r''
result_b = r''
# %% About
# - Name: RE Syntax Anchor
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Define `result_a: str` with regular expression pattern to find
# character at the end of a text
# example: ['.']
# 2. Define `result_b: str` with regular expression pattern to find
# character at the end of each line
# example: ['d', 'e', 'n', 'n', ',', '.']
# 3. Define only regex pattern (str), not re.findall(...)
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result_a: str` z wzorcem wyrażenia regularnego aby wyszukać
# znak na końcu tekstu
# przykład: ['.']
# 2. Zdefiniuj `result_b: str` z wzorcem wyrażenia regularnego aby wyszukać
# znak na końcu każdej linii
# przykład: ['d', 'e', 'n', 'n', ',', '.']
# 3. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% References
# [1] Authors: Wikipedia contributors
# Title: Apollo 11
# Publisher: Wikipedia
# Year: 2019
# Retrieved: 2019-12-14
# URL: https://en.wikipedia.org/wiki/Apollo_11
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> result = re.findall(result_a, DATA, flags=re.MULTILINE)
>>> pprint(result, compact=True)
['.']
>>> result = re.findall(result_b, DATA, flags=re.MULTILINE)
>>> pprint(result, compact=True)
['d', 'e', 'n', 'n', ',', '.', 'd', 's', 's', 'e', 'n', '.']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import re
# %% Types
result_a: str
result_b: str
# %% Data
DATA = """Apollo 11 was the American spaceflight that first landed
humans on the Moon. Commander (CDR) Neil Armstrong and lunar module
pilot (LMP) Buzz Aldrin landed the Apollo Lunar Module (LM) Eagle on
July 20th, 1969 at 20:17 UTC, and Armstrong became the first person
to step (EVA) onto the Moon's surface (EVA) 6 hours 39 minutes later,
on July 21st, 1969 at 02:56:15 UTC. Aldrin joined him 19 minutes later.
They spent 2 hours 31 minutes exploring the site they had named
Tranquility Base upon landing. Armstrong and Aldrin collected 47.5 pounds
(21.5 kg) of lunar material to bring back to Earth as pilot Michael Collins
(CMP) flew the Command Module (CM) Columbia in lunar orbit, and were on the
Moon's surface for 21 hours 36 minutes before lifting off to rejoin
Columbia."""
# %% Result
result_a = r''
result_b = r''