Pattern patron=Pattern.compile("expresionRegular");
Matcher ma=patron.matcher(String a evaluar);
luego para saber si la cadena dada para crear el matcher cumple se utiliza el siguiente método boleano:
ma.matches();
las reglas para hacer las expresiones regulares son muy similares a lo que vimos en clase, las principales son más o menos estas:
| . | Any character (may or may not match line terminators) |
| \d | A digit: [0-9] |
| \D | A non-digit: [^0-9] |
| \s | A whitespace character: [ \t\n\x0B\f\r] |
| \S | A non-whitespace character: [^\s] |
| \w | A word character: [a-zA-Z_0-9] |
| \W | A non-word character: [^\w] |
| [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) |
| X? | X, once or not at all |
| X* | X, zero or more times |
| X+ | X, one or more times |
| X{n} | X, exactly n times |
| X{n,} | X, at least n times |
| X{n,m} | X, at least n but not more than m times |
por ejemplo: revisar si el formato de una fecha del tipo dd/mm/aaaa es correcta
Pattern patron=Pattern.compile(""[0-3]\\d/[0-1][0-2]/\\d{4}");/*se pone doble backslash porque si no \d lo toma como un escape*/
Matcher ma=patron.matcher(String que debe ser una fecha);
boolean b=ma.matches;
si String que debe ser una fecha="01/03/1998" entonces b==true;
si String que debe ser una fecha="02/13/2009" entonces B==false;
para mas información: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
No hay comentarios:
Publicar un comentario