CKTIS / Python
re.sub
Sostituisce da sinistra le corrispondenze non sovrapposte.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
re.sub(pattern, repl, string, count=0, flags=0)Sostituisce da sinistra le corrispondenze non sovrapposte.
Nel modello una sequenza sconosciuta di barra inversa e lettera ASCII come \q solleva re.PatternError. La stessa stringa restituita da una funzione resta letterale. Una stringa repl è un modello che può riferirsi ai gruppi, una funzione riceve un Match e fornisce direttamente la sostituzione. count=0 permette tutte le sostituzioni.
Nell’esempio count=1 limita l’incremento al primo numero 3 e il risultato è x4 y7.
import re
assert re.sub(r"(\w+)=(\d+)", r"\2:\1", "x=3") == "3:x"
assert re.sub(r"\d+", lambda m: str(int(m[0]) + 1), "x3 y7", count=1) == "x4 y7"
assert re.sub("z", "x", "abc") == "abc"
try:
re.sub("a", r"\q", "a")
except re.PatternError:
pass
else:
raise AssertionError
assert re.sub("a", lambda m: r"\q", "a") == r"\q"
Esempi
import re
print(re.sub(r"\d+", lambda m: str(int(m.group()) + 1), "x3 y7", count=1))
Risultato
x4 y7
Nell’esempio count=1 limita l’incremento al primo numero 3 e il risultato è x4 y7.