javaRegex學習筆記(四)

來源:互聯網
上載者:User

  接著學習java.util.regex包裡關於Regex的包,因為string類只提供部分Regex的功能,不能充

分展現Regex強大的功能.
  java.util.regex包裡有兩個類,一個介面,一個異常,Regex的主要功能都是在Pattern,Matcher兩個

類裡實現了,現在先學習Pattern類,Pattern類一共有8個方法和兩個方法的重載,還有8個欄位,下面直接看

一個例子你就明白他的原理,如果不明白可以查看JDK的協助.

import java.util.regex.Pattern;
import java.util.regex.Matcher;
//compile(),split(),flags(),matcher(),matches(),quote(),toString(),pattern()
class PatternTest{
public static void main(String[] args){
String regex = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+[.]((net)|(com)|(com.cn)|(cn))$";
Pattern p = Pattern.compile(regex);
String result = p.pattern();
p(result);
p(p.flags());
result = p.toString();
p(result);

String regex1 = "mx";
Pattern p1 = Pattern.compile(regex1);
Matcher m1 = p1.matcher("abcdefgABCDEFG");
while(m1.find()){
p(m1.group());//abc
}
Pattern p2 = Pattern.compile(regex1,Pattern.CASE_INSENSITIVE);
Matcher m2 = p2.matcher("abcdefgABCDEFG");
while(m2.find()){
p(m2.group());//abc ABC
}

p(p2.flags());

boolean b ;
b = Pattern.matches(regex,"lovefeel2004@126.com");
p(b);

p(Pattern.quote("lovefeel2004@126.com"));

Pattern p3 = Pattern.compile("@");
String[] result1 = p3.split("love@feel@2004@com@cn");
for(String s: result1){
p(s);
}

result1 = p3.split("love@feel@2004@com@cn",3);
for(String s: result1){
p(s);
}
}

public static void p(Object o){
System.out.println(o);
}
}

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.