Riferimenti all'indietro

Esternamente ad una classe di caratteri, un backslah (\) seguito da una o più cifre maggiori di 0 è un riferimento all'indietro verso testi catturati precedentemente (ad esempio alla sinistra rispetto a dove ci si trova), conteggiati tramite il numero delle parentesi chiuse precedenti.

Tuttavia, se il numero che segue il backslash (\) è un valore inferiore a 10, si assume che si tratti sempre di un riferimento all'indietro, e pertanto viene generato un errore se nel criterio non vi sono almeno altrettante parentesi chiuse di sotto-regole di cattura. In altre parole per i numeri inferiori a 10 non è necessario che il numero parentesi precedenti (a sinistra) alla sotto-regola sia pari o maggiore al numero indicato. Un "riferimento all'indietro e all'avanti" ha senso quando è presente una ripetizione e la sotto-regola alla destra ha partecipato a un'iterazione precedente. Vedere la sezione relativa al backslash per informazioni su come gestire le cifre seguenti il backslash.

Un riferimento all'indietro identifica ciò che è già stato catturato dalla sotto-regola, e non ciò che la sotto-regola stessa possa riconoscere. Ad esempio il criterio (sens|respons)e and \1ibility può riconoscere "sense and sensibility" oppure "response and responsibility", ma non il testo "sense and responsibility". Se al momento del riferimento all'indietro, è attiva la distinzione tra lettere maiuscole e minuscole, il formato della lettera diventa rilevante. Ad esempio, ((?i)rah)\s+\1 può identificare "rah rah" e "RAH RAH", ma non "RAH rah", anche se la sotto-regola originale eseguiva dei riconoscimenti a prescindere dalle lettere maiuscole e minuscole.

Nella medesima sotto-regola si possono avere più di un riferimento all'indietro. Se una sotto-regola non viene utilizzata in un particolare riconoscimento, un riferimento a questa ha sempre esito negativo. Ad esempio il criterio (a|(bc))\2 non avrà mai successo se l'identificazione della stringa inizia con "a" e non con "bc". Dato che sono possibili fino a 99 riferimenti all'indietro, tutte le cifre che seguono un backslash (\) sono considerate come parte di un potenziale numero di riferimento. Se il criterio continua con altri caratteri numerici, occorre stabilire un carattere per delimitare il numero del riferimento. Se si attiva l'opzione PCRE_EXTENDED questo carattere può essere lo spazio. Altrimenti si può usare un commento vuoto.

Un riferimento all'indietro non ha successo se viene inserito in una sotto regola prima che sia applicata. Con questo si intende, ad esempio, che (a\1) non avrà mai successo, ma, nel caso di una sottoregola ripetuta, si avrà un riscontro positivo. Ad esempio (a|b\1)+ identificherà qualsiasi numero di "a", ma anche "aba" oppure "ababaa" ecc. In pratica a ciascuna iterazione della sotto-regola il riferimento andrà a sostituire la stringa riconosciuta tramite la sotto-regola dell'iterazione precedente. Affinchè il tutto funzioni, è necessario che la prima iterazione sia identificata senza l'ausilio del riferimento "all'indietro". Ciò può essere ottenuto o usando casi alternativi, come nell'esempio precedente, o usando le occorrenze indicando come numero minimo di occorrenze il valore zero.

Dal PHP 5.2.2, la sequenza di escape \g può essere utilizzata per referenziare sottoregole assolute e relative. Questa sequenza di escape deve essere seguita da un numero senza segno o un numero negativo, eventualmente racchiuso in parentesi graffe. Le sequenze \1, \g1 e \g{1} sono tra loro sinonimi. L'uso di questa regola con numeri senza segno può aiutare a rimuovere l'ambiguità creata quando si usano numeri che seguono un backslash. Questa sequenza permette di distinguere i riferimenti all'indietro dai caratteri ottali e permette anche di avere più facilmente un riferimento all'indietro seguito da un numero letterale, es. \g{2}1.

L'utilizzo della sequenza \g con un numero negativo significa riferimento negativo. Per esempio, (foo)(bar)\g{-1} identifica la sequenza "foobarbar" e (foo)(bar)\g{-2} identifica "foobarfoo". Questo può essere utile in regole lunghe come un'alternativa per tener nota del numero di sotto-regole, al fine di far riferimento a una specifica sottoregola precedente.

I riferimenti all'indietro a sotto-regole con nome possono essere ottenuti con (?P=name) o, da PHP 5.2.2, anche con \k<name> o \k'name'. PHP 5.2.4 ha inoltre aggiunto il supporto per \k{name} e \g{name}.

add a note

User Contributed Notes 2 notes

up
13
mnvx at yandex dot ru
7 years ago
Something similar opportunity is DEFINE.

Example:
(?(DEFINE)(?<myname>\bvery\b))(?&myname)\p{Pd}(?&myname).

Expression above will match "very-very" from next sentence:
Define is very-very handy sometimes.
^-------^

How it works. (?(DEFINE)(?<myname>\bvery\b)) - this block defines "myname" equal to "\bvery\b". So, this block "(?&myname)\p{Pd}(?&myname)" equvivalent to "\bvery\b\p{Pd}\bvery\b".
up
0
Steve
1 year ago
The escape sequence \g used as a backreference may not always behave as expected.
The following numbered backreferences refer to the text matching the specified capture group, as documented:
\1
\g1
\g{1}
\g-1
\g{-1}

However, the following variants refer to the subpattern code instead of the matched text:
\g<1>
\g'1'
\g<-1>
\g'-1'

With named backreferences, we may also use the \k escape sequence as well as the (?P=...) construct. The following combinations also refer to the text matching the named capture group, as documented:
\g{name}
\k{name}
\k<name>
\k'name'
(?P=name)

However, these refer to the subpattern code instead of the matched text:
g<name>
\g'name'

In the following example, the capture group searches for a single letter 'a' or 'b', and then the backreference looks for the same letter. Thus, the patterns are expected to match 'aa' and 'bb', but not 'ab' nor 'ba'.

<?php
/* Matches to the following patterns are replaced by 'xx' in the subject string 'aa ab ba bb'. */
$patterns = [
# numbered backreferences (absolute)
'/([ab])\1/', // 'xx ab ba xx'
'/([ab])\g1/', // 'xx ab ba xx'
'/([ab])\g{1}/', // 'xx ab ba xx'
'/([ab])\g<1>/', // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
"/([ab])\g'1'/", // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
'/([ab])\k{1}/', // 'aa ab ba bb' # No group with name "1", backreference to unset group always fails.
'/([ab])\k<1>/', // 'aa ab ba bb' # No group with name "1", backreference to unset group always fails.
"/([ab])\k'1'/", // 'aa ab ba bb' # No group with name "1", backreference to unset group always fails.
'/([ab])(?P=1)/', // NULL # Regex error: "subpattern name must start with a non-digit", (?P=) expects name not number.
# numbered backreferences (relative)
'/([ab])\-1/', // 'aa ab ba bb'
'/([ab])\g-1/', // 'xx ab ba xx'
'/([ab])\g{-1}/', // 'xx ab ba xx'
'/([ab])\g<-1>/', // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
"/([ab])\g'-1'/", // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
'/([ab])\k{-1}/', // 'aa ab ba bb' # No group with name "-1", backreference to unset group always fails.
'/([ab])\k<-1>/', // 'aa ab ba bb' # No group with name "-1", backreference to unset group always fails.
"/([ab])\k'-1'/", // 'aa ab ba bb' # No group with name "-1", backreference to unset group always fails.
'/([ab])(?P=-1)/', // NULL # Regex error: "subpattern name expected", (?P=) expects name not number.
# named backreferences
'/(?<name>[ab])\g{name}/', // 'xx ab ba xx'
'/(?<name>[ab])\g<name>/', // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
"/(?<name>[ab])\g'name'/", // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
'/(?<name>[ab])\k{name}/', // 'xx ab ba xx'
'/(?<name>[ab])\k<name>/', // 'xx ab ba xx'
"/(?<name>[ab])\k'name'/", // 'xx ab ba xx'
'/(?<name>[ab])(?P=name)/', // 'xx ab ba xx'
];

foreach (
$patterns as $pat)
echo
" '$pat',\t// " . var_export(@preg_replace($pat, 'xx', 'aa ab ba bb'), 1) . PHP_EOL;
?>
To Top