tcl
Espressioni regolari
Ricerca…
Sintassi
- regexp? switch? exp string? matchVar? ? subMatchVar subMatchVar ...?
- regsub? switch? exp string subSpec? varName?
Osservazioni
Questo argomento non ha lo scopo di discutere le stesse espressioni regolari. Ci sono molte risorse su internet che spiegano espressioni regolari e strumenti per aiutare a costruire espressioni regolari.
Questo argomento proverà a coprire i comuni switch e metodi di utilizzo delle espressioni regolari in Tcl e alcune delle differenze tra Tcl e altri motori di espressioni regolari.
Le espressioni regolari sono generalmente lente. La prima domanda che dovresti fare è "Ho davvero bisogno di un'espressione regolare?". Abbina solo quello che vuoi. Se non hai bisogno degli altri dati, non abbinarli.
Per gli scopi di questi esempi di espressioni regolari, verrà utilizzata l'opzione -expanded per poter commentare e spiegare l'espressione regolare.
accoppiamento
Il comando regexp viene utilizzato per associare un'espressione regolare a una stringa.
# This is a very simplistic e-mail matcher.
# e-mail addresses are extremely complicated to match properly.
# there is no guarantee that this regex will properly match e-mail addresses.
set mydata "send mail to [email protected] please"
regexp -expanded {
\y # word boundary
[^@\s]+ # characters that are not an @ or a space character
@ # a single @ sign
[\w.-]+ # normal characters and dots and dash
\. # a dot character
\w+ # normal characters.
\y # word boundary
} $mydata emailaddr
puts $emailaddr
[email protected]
Il comando regexp restituirà un valore 1 (true) se è stata eseguita una corrispondenza o 0 (false) in caso contrario.
set mydata "hello wrld, this is Tcl"
# faster would be to use: [string match *world* $mydata]
if { [regexp {world} $mydata] } {
puts "spelling correct"
} else {
puts "typographical error"
}
Per abbinare tutte le espressioni in alcuni dati, utilizzare l'opzione -all e l'opzione -inline per restituire i dati. Si noti che l'impostazione predefinita è il trattamento di nuove righe come qualsiasi altro dato.
# simplistic english ordinal word matcher.
set mydata {
This is the first line.
This is the second line.
This is the third line.
This is the fourth line.
}
set mymatches [regexp -all -inline -expanded {
\y # word boundary
\w+ # standard characters
(?:st|nd|rd|th) # ending in st, nd, rd or th
# The ?: operator is used here as we don't
# want to return the match specified inside
# the grouping () operator.
\y # word boundary
} $mydata]
puts $mymatches
first second third fourth
# if the ?: operator was not used, the data returned would be:
first st second nd third rd fourth th
Manipolazione a Newline
# find real numbers at the end of a line (fake data).
set mydata {
White 0.87 percent saturation.
Specular reflection: 0.995
Blue 0.56 percent saturation.
Specular reflection: 0.421
}
# the -line switch will enable newline matching.
# without -line, the $ would match the end of the data.
set mymatches [regexp -line -all -inline -expanded {
\y # word boundary
\d\.\d+ # a real number
$ # at the end of a line.
} $mydata]
puts $mymatches
0.995 0.421
Unicode non richiede alcuna gestione speciale.
% set mydata {123ÂÃÄÈ456}
123ÂÃÄÈ456
% regexp {[[:alpha:]]+} $mydata match
1
% puts $match
ÂÃÄÈ
% regexp {\w+} $mydata match
1
% puts $match
123ÂÃÄÈ456
Documentazione: regexp re_syntax
Mischiare quantificatori avidi e non grezzi
Se hai una partita avida come primo quantificatore, l'intero RE sarà avido,
Se hai una corrispondenza non avida come primo quantificatore, l'intero RE non sarà avido.
set mydata {
Device widget1: port: 156 alias: input2
Device widget2: alias: input1
Device widget3: port: 238 alias: processor2
Device widget4: alias: output2
}
regexp {Device\s(\w+):\s(.*?)alias} $mydata alldata devname devdata
puts "$devname $devdata"
widget1 port: 156 alias: input2
regexp {Device\s(.*?):\s(.*?)alias} $mydata alldata devname devdata
puts "$devname $devdata"
widget1 port: 156
Nel primo caso, il primo \ w + è avido, quindi tutti i quantificatori sono contrassegnati come avidi e il. *? corrisponde più del previsto
Nel secondo caso, il primo. *? è non-goloso e tutti i quantificatori sono contrassegnati come non-golosi.
Altri motori di espressioni regolari potrebbero non avere problemi con quantificatori avidi / non grezzi, ma sono molto più lenti.
Henry Spencer ha scritto : ... Il problema è che è molto, molto difficile scrivere una generalizzazione di quelle affermazioni che coprono espressioni regolari di avidità mista - una definizione corretta, indipendente dall'implementazione di ciò che le espressioni regolari di avidità mista dovrebbero corrispondere - - e li fa fare "ciò che la gente si aspetta". Ho provato. Ci sto ancora provando Nessuna fortuna finora. ...
Sostituzione
Il comando regsub viene utilizzato per la corrispondenza e la sostituzione delle espressioni regolari.
set mydata {The yellow dog has the blues.}
# create a new string; only the first match is replaced.
set newdata [regsub {(yellow|blue)} $mydata green]
puts $newdata
The green dog has the blues.
# replace the data in the same string; all matches are replaced
regsub -all {(yellow|blue)} $mydata red mydata
puts $mydata
The red dog has the reds.
# another way to create a new string
regsub {(yellow|blue)} $mydata red mynewdata
puts $mynewdata
The red dog has the blues.
Utilizzo di riferimenti precedenti per referenziare i dati corrispondenti.
set mydata {The yellow dog has the blues.}
regsub {(yellow)} $mydata {"\1"} mydata
puts $mydata
The "yellow" dog has the blues.
Documentazione: regsub re_syntax
Differenze tra il motore RE di Tcl e altri motori RE.
- \ m: inizio di una parola.
- \ M: fine di una parola.
- \ y: confine di parole.
- \ Y: un punto che non è un limite di parole.
- \ Z: corrisponde alla fine dei dati.
Documentazione: re_sintassi
Abbinare una stringa letterale a un'espressione regolare
A volte è necessario abbinare una stringa (sotto) letterale con un'espressione regolare nonostante quella sottostringa contenente metacaratteri RE. Mentre sì, è possibile scrivere codice per inserire backslash appropriati per fare quel lavoro (usando string map ) è più semplice precedere il modello con ***= , il che rende il motore RE che tratta il resto della stringa come caratteri letterali , disabilitando tutti gli altri metacaratteri.
set sampleText "This is some text with \[brackets\] in it."
set searchFor {[brackets]}
if {[ regexp ***=$searchFor $sampleText ]} {
# This message will be printed
puts "Found it!"
}
Nota che questo significa anche che non puoi usare nessuno degli ancoraggi.