Modo semplice e personalizzabile per effettuare controlli sui set di carateri permessi:
Le regex,in inglese "Regular expression",sono un insieme di regole sintattiche attraverso le quali possiamo rappresentare insiemi di stringhe. La sintassi del Java per le più importanti regole grammaticali per l'implementazione delle Regex (
Riferimento completo delle regole):
Characters
x The character x
\\ The backslash character
\0n The character with octal value 0n (0 <= n <= 7)
\0nn The character with octal value 0nn (0 <= n <= 7)
\0mnn The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
\xhh The character with hexadecimal value 0xhh
\uhhhh The character with hexadecimal value 0xhhhh
\t The tab character ('\u0009')
\n The newline (line feed) character ('\u000A')
\r The carriage-return character ('\u000D')
\f The form-feed character ('\u000C')
\a The alert (bell) character ('\u0007')
\e The escape character ('\u001B')
\cx The control character corresponding to x
Character classes
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a-zA-Z] a through z or A through Z, inclusive (range)
[a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]] d, e, or f (intersection)
[a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)
In Java per poter utilizzare le regular expression bisogna importare il package:
- Codice:
-
java.util.regex.*; //può essere serializzato
Fatto questo bisogna definire un Pattern cioè quell'insieme di regole su citate quindi scriviamo:
- Codice:
-
Pattern p = Pattern.compile(regola);
Matcher m = p.matcher(stringa);
boolean b = m.matches();
Si è definito un pattern con la regola che ci serve,ad esmpio [a-z]che serve per poter accettare caratteri minuscoli che vanno da 'a' a 'z' estremi inclusi.Fatto questo con la riga "
Matcher m=p.matcher(stringa)" si definisce appunto dove questa sequenza di caratteri deve essere cercata e con l'ultima opzione viene effettuato un confronto e restituito un valore booleano che indicherà l'esito dello stesso.
Un'altro metodo sintattico per le regex si trova nel metodo matcher che può ricevere la stringa Regex e la sequenza di dati così utilizzata:
- Codice:
-
boolean b=Pattern.matches(regex, input);
Restituirà sempre un valore booleano indicativo per il confronto avvenuto.
Questa sintassi è utilissima perchè permette di controllare il flusso di dati nel programma senza che si scriva tanto codice
Per ulteriori informazioni c'è la
Guida Sun java.util.regex