1 private static Pattern datePattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}"); 2 public static boolean checkDate(String date){ 3 Matcher m = datePattern.matcher(date); 4 if(m.find()){ 5 return true; 6 } 7 return false; 8 } 9 10 public class Test { 11 public static void main(String[] args) 12 { 13 Pattern p=Pattern.compile("a"); 14 Matcher m=p.matcher("aaa"); 15 int count=0; 16 while(m.find()) 17 { 18 count++; 19 } 20 System.out.println(count); 21 } 22 }
表達式規則:正則表達式
字符
x 字符 x
\\ 反斜線字符
\0n 八進制值的字符0n (0 <= n <= 7)
\0nn 八進制值的字符 0nn (0 <= n <= 7)
\0mnn 八進制值的字符0mnn 0mnn (0 <= m <= 3, 0 <= n <= 7)
\xhh 十六進制值的字符0xhh
\uhhhh 十六進制值的字符0xhhhh
\t 製表符('\u0009')
\n 換行符 ('\u000A')
\r 回車符 ('\u000D')
\f 換頁符 ('\u000C')
\a 響鈴符 ('\u0007')
\e 轉義符 ('\u001B')
\cx T對應於x的控制字符 x
字符類
[abc] a, b, or c (簡單類)
[^abc] 除了a、b或c以外的任意 字符(求反)
[a-zA-Z] a到z或A到Z ,包含(範圍)
[a-z-[bc]] a到z,除了b和c : [ad-z](減去)
[a-z-[m-p]] a到z,除了m到 p: [a-lq-z]
[a-z-[^def]] d, e, 或 f
備註:
方括號的正則表達式「t[aeio]n」只匹配「tan」、「Ten」、「tin」和「ton」,只能匹配單個字符。
圓括號,由於方括號只容許匹配單個字符;故匹配多個字符時使用圓括號「()」。好比使用「t(a|e|i|o|oo)n」正則表達式,就必須用圓括號。spa
預約義的字符類
. 任意字符(也許能與行終止符匹配,也許不能) 備註:句點符號表明任意一個字符。好比:表達式就是「t.n」,它匹配「tan」、「ten」、「tin」和「ton」,還匹配「t#n」、「tpn」甚至「t n」。
\d 數字: [0-9]
\D 非數字: [^0-9]
\s 空格符: [ \t\n\x0B\f\r]
\S 非空格符: [^\s]
\w 單詞字符: [a-zA-Z_0-9]
\W 非單詞字符: [^\w]code
表達次數的符號
符號 次數
* 0次或者屢次
+ 1次或者屢次
? 0次或者1次
{n} 剛好n次
{n,m} 從n次到m次blog
1 String strNow1 = "2016-12-01 13:46"; 2 strNow1 = strNow1.replaceAll("\\s|-|/|:","");
管道。io