Match String Prefix with re.prefixmatch in Python 3.15

Match String Prefix with re.prefixmatch in Python 3.15

The re module provides match for testing whether a pattern appears at the beginning of a string. The name is a long-standing source of confusion, because in most other languages and regular expression libraries "match" means finding a pattern anywhere in the string, which in Python is the job of search. In Python, match succeeds only if the pattern appears at the start of the string.

For example, two patterns are be tested against the same log line:

import re

line = '2026-10-14 ERROR disk full'

# <re.Match object; span=(0, 10), match='2026-10-14'>
print(re.match(r'\d{4}-\d{2}-\d{2}', line))
# None
print(re.match(r'ERROR', line))

The date is found because it begins the string. The second call returns None even though the string plainly contains ERROR, since the pattern does not start at the beginning. Developers arriving from another language typically expect this call to succeed, which is what makes the name misleading.

Since Python 3.15, the same behaviour is available under the name prefixmatch, which states what the function actually does.

import re

line = '2026-10-14 ERROR disk full'

# <re.Match object; span=(0, 10), match='2026-10-14'>
print(re.prefixmatch(r'\d{4}-\d{2}-\d{2}', line))
# None
print(re.prefixmatch(r'ERROR', line))

The results are identical, because prefixmatch is a second name for the same function rather than a change in behaviour. The same applies to compiled patterns, where Pattern.match is also available as Pattern.prefixmatch.

The match name is soft deprecated as of Python 3.15. It is not removed, existing code still works.

Leave a Comment

Cancel reply

Your email address will not be published.