Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

re.Pattern

A compiled pattern stores the expression and flags and exposes methods for repeated searches.

Version: Python 3.14; repository image, production runtime not attested

Syntax

p = re.compile(pattern)
p.search(string, pos, endpos)

A compiled pattern stores the expression and flags and exposes methods for repeated searches.

A search with a starting position retains offsets into the original string, making match spans reusable.

A compiled Pattern keeps the source, flags and capture metadata. Its search method accepts pos and endpos to limit a search without creating a substring. Match spans still index the original input. pos does not redefine the absolute start for ^. Starting at position 1 skips the first digit and finds 17 at (3, 5). Inspect pattern for the source, flags for effective options, groups for the capturing-group count and groupindex for the mapping of group names to numbers.

import re
p = re.compile("ab")
assert isinstance(p, re.Pattern)
assert p.search("ab-ab", 1, 5).span() == (3, 5)
assert p.search("ab-ab", 1, 4) is None
assert re.compile("^ab").search("xaba", 1) is None
p = re.compile(r"(?P<id>\d+)", re.I)
assert p.pattern == r"(?P<id>\d+)" and p.flags & re.I and p.groups == 1 and p.groupindex == {"id": 1}

re.Pattern.fullmatch · re.Pattern.search · re.Pattern.sub

fullmatch requires the entire selected range and search finds its first match. Both return Match or None. sub replaces non-overlapping matches with a template or the result of calling a function on each Match. A positive count limits replacements.

import re
p=re.compile(r'[A-Z]+')
assert p.fullmatch('QA').group()=='QA' and p.fullmatch('id QA') is None
assert p.search('id QA').span()==(3,5) and p.search('id') is None
assert p.sub(lambda m:m.group().lower(),'QA: DEV',count=1)=='qa: DEV'

Examples

import re
pattern = re.compile(r"\d+")
print(isinstance(pattern, re.Pattern))
print(pattern.search("3 a17", 1).span())

Result

True
(3, 5)

A compiled Pattern keeps the source, flags and capture metadata. Its search method accepts pos and endpos to limit a search without creating a substring. Match spans still index the original input. pos does not redefine the absolute start for ^. Starting at position 1 skips the first digit and finds 17 at (3, 5). Inspect pattern for the source, flags for effective options, groups for the capturing-group count and groupindex for the mapping of group names to numbers.

Sources