-------
android培訓、java培訓、期待與您交流! ----------
Regex用來操作字串資料。
字元類
[abc] a、b 或 c(簡單類)
[^abc] 任何字元,除了 a、b 或 c(否定)
[a-zA-Z] a 到 z 或 A 到 Z,兩頭的字母包括在內(範圍)
[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](並集)
[a-z&&[def]] d、e 或 f(交集)
[a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](減去)
[a-z&&[^m-p]] a 到 z,而非 m 到 p:[a-lq-z](減去)
預定義字元類
. 任何字元(與行結束符可能匹配也可能不匹配)
\d 數字:[0-9]
\D 非數字: [^0-9]
\s 空白字元:[ \t\n\x0B\f\r]
\S 非空白字元:[^\s]
\w 單詞字元:[a-zA-Z_0-9]
\W 非單詞字元:[^\w]
邊界匹配器
^ 行的開頭
$ 行的結尾
\b 單詞邊界
\B 非單詞邊界
\A 輸入的開頭
\G 上一個匹配的結尾
\Z 輸入的結尾,僅用於最後的結束符(如果有的話)
\z 輸入的結尾
Greedy 數量詞
X? X,一次或一次也沒有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超過 m 次
擷取的群組(.),引用\\1,引用上一個參數的組$1
常見操作:
1、匹配
String str = "asdfg";
String regex = "\w{5}";
Boolean b = str.matchs(regex);//---匹配結果b為true
2、切割
String regex = "d";
String[] strs = str.split(regex);
3、替換
String tel = "15800001111";//158****1111;
tel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
4、尋找
String str = "da jia hao,ming tian bu fang jia!";
String regex = "\\b[a-z]{3}\\b";
//1,將正則封裝成對象。
Pattern p = Pattern.compile(regex);
//2, 通過正則對象擷取匹配器對象。
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group());//擷取匹配的子序列
System.out.println(m.start()+":"+m.end());
}
擷取網頁中郵箱程式
public static List<String> getMailsByWeb() throws IOException {URL url = new URL("http://192.168.1.66:8080/myweb/mail.html");BufferedReader bufIn = new BufferedReader(new InputStreamReader(url.openStream()));//2,對讀取的資料進行規則的匹配。從中擷取符合規則的資料.String mail_regex = "\\w+@\\w+(\\.\\w+)+";List<String> list = new ArrayList<String>();Pattern p = Pattern.compile(mail_regex);String line = null;while((line=bufIn.readLine())!=null){Matcher m = p.matcher(line);while(m.find()){//3,將符合規則的資料存放區到集合中。list.add(m.group());}}return list;}
-------
android培訓、java培訓、期待與您交流! ----------