Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

Expressões regulares

Um padrão descreve a estrutura de texto e fullmatch exige correspondência com a cadeia inteira.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

match = re.fullmatch(r'([A-Z]+)-([0-9]+)', text)

Um padrão descreve a estrutura de texto e fullmatch exige correspondência com a cadeia inteira.

search pode encontrar uma subcadeia. Os grupos capturam texto sem conversão. [0-9] limita os dígitos a ASCII, enquanto \d num padrão str normalmente reconhece outros dígitos decimais Unicode.

QA-07 dá ('QA', '07') preservando o zero. Um prefixo e um dígito de largura total dão None.

import re
p=re.compile(r'(?P<team>[A-Z]+)-(?P<number>[0-9]+)')
m=p.search('id QA-07!')
assert m.group('number')=='07' and m.span()==(3,8)
assert p.fullmatch('id QA-07!') is None
assert re.fullmatch(r'\d','7') and not re.fullmatch(r'[0-9]','7')

Exemplos

import re

pattern = re.compile(r"(?P<team>[A-Z]+)-(?P<number>[0-9]+)")
for text in ["QA-07", "prefix QA-07", "QA-7"]:
    match = pattern.fullmatch(text)
    print(match.groups() if match else None)

Resultado

('QA', '07')
None
None

QA-07 dá ('QA', '07') preservando o zero. Um prefixo e um dígito de largura total dão None.

Fontes