The $
character always matches the end of the input string.
In Multi-line mode (e.g. when re.M
is passed as a flag to one of the re
functions), it also matches the end of each line of a multiple line input, just before the newline character.
You want an example with re.match
:
some_string = "foo bar baz"
if re.match("foo.*baz$", some_string):
print("Starts with foo and ends with baz") # this will be printed
The $
character in the pattern here ensures that the baz
that gets matched occurs right at the end of the input string. That pattern wouldn't match a string like "foo baz bar"
, since even though baz
occurs, it isn't at the end of the input.
It's not usually useful to call re.match
with the multi-line flag set. Instead, you'd more commonly do that with something like re.findall
:
multi_line_string = """
foo
bar
foobar
barrel"""
for match in re.findall("^bar$", re.M):
print("bar is whole line") # this will get printed only once
The ^
and $
characters in the pattern given to re.findall
make sure that bar
is the whole contents of the line that gets matched. Without them, foobar
and barrel
would also match.