標籤:
下表顯示了Regex的文法: 表 1.1 Regex文法
| 元字元 |
說明 |
| . |
匹配任何單個字元。例如Regex“b.g”能匹配如下字串:“big”、“bug”、“b g”,但是不匹配“buug”。 |
| $ |
匹配行結束符。例如Regex“EJB$”能夠匹配字串“I like EJB”的末尾,但是不能匹配字串“J2EE Without EJBs!”。 |
| ^ |
匹配一行的開始。例如Regex“^Spring”能夠匹配字串“Spring is a J2EE framework”的開始,但是不能匹配“I use Spring in my project”。 |
| * |
匹配0至多個在它之前的字元。例如Regex“zo*”能匹配“z”以及“zoo”;Regex“.*”意味著能夠匹配任一字元串。 |
| / |
轉義符,用來將元字元當作普通的字元來進行匹配。例如Regex/$被用來匹配貨幣符號,而不是行尾;Regex/.用來匹配點字元,而不是任何字元的萬用字元。 |
| [] |
匹配括弧中的任何一個字元。例如Regex“b[aui]g”匹配bug、big和bug,但是不匹配beg。可以在括弧中使用連字號“-”來指定字元的區間來簡化表示,例如Regex[0-9]可以匹配任何數字字元,這樣Regex“a[]c”就可以匹配“a0c”、“a1c”、“a2c”等字串;還可以制定多個區間,例如“[A-Za-z]”可以匹配任何大小寫字母。還有一個相配合使用的元字元“^”,用在這裡並不像前邊的那個“^”一樣表示匹配行開始,而是表示“排除”,要想匹配除了指定區間之外的字元,就可以在左邊的括弧和第一個字元之間使用^字元,例如“[^163A-Z]”將能偶匹配除了1、6、3和所有大寫字母之外的任何字元。 |
| ( ) |
將 () 之間括起來的運算式定義為“組”(group),並且將匹配這個運算式的字元儲存到一個臨時地區,這個元字元在字串提取的時候非常有用。 |
| | |
將兩個匹配條件進行邏輯“或”運算。‘z|food‘ 能匹配 "z" 或 "food"。‘(z|f)ood‘ 則匹配"zood" 或 "food"。 |
| + |
匹配前面的子運算式一次或多次。例如Regex9+匹配9、99、999等。 |
| ? |
匹配前面的子運算式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 中的"do" 。此元字元還有另外一個用途,就是表示非貪婪模式比對,後邊將有介紹 |
| {n} |
匹配確定的 n 次。例如,“e{2}”不能匹配“bed”中的“d”,但是能匹配“seed”中的兩個“e”。 |
| {n,} |
至少匹配n次。例如,“e{2,}”不能匹配“bed”中的“e”,但能匹配“seeeeeeeed”中的所有“e”。 |
| {n,m} |
最少匹配 n 次且最多匹配 m 次。“e{1,3}”將匹配“seeeeeeeed”中的前三個“e”。 |
|
測試代碼:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str="bbg";
Pattern pattern = Pattern.compile("(b*g)");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.matches());
System.out.println(pattern.matches("b*g","bbg"));
System.out.println(pattern.matches("[0-9]{6}", "200038"));
System.out.println(pattern.matches("//d{6}", "200038"));
//驗證電話號碼
System.out.println(pattern.matches("[0-9]{3,4}//-?[0-9]+", "021-78989799"));
getString("D:/dir1/test.txt");
getChinese("welcome to china,江西奉新,welcome,你!");
}
public static void getString(String str){
String regex = ".+/(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if(!matcher.find()){
System.out.println("檔案路徑格式不正確!");
return;
}
System.out.println(matcher.group(1));
}
public static void getChinese(String str){
String regex = "[//u4E00-//u9FFF]+";//[//u4E00-//u9FFF]為漢字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
sb.append(matcher.group());
}
System.out.println(sb);
}
public static void validateEmail(String email){
String regex = "[0-9a-zA-Z][email protected][0-9a-zA-Z]+//.[0-9a-zA-Z]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
if(matcher.matches()){
System.out.println("這是合法的Email");
}else{
System.out.println("這是非法的Email");
}
}
}
java Regex