JavaSE基礎:Regex

來源:互聯網
上載者:User

  -------
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培訓、期待與您交流! ----------

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.