正則表達

正則表達式

正則表達式:其實一種規則,有本身特殊的應用,其做用就是針對於字符串進行操做。html

正則:就是用於操做字符串的規則,其中這些規則使用了一些字符表示。web

 

1.1 快速體驗正則表達式

需求:只能輸入數字正則表達式

public class Demo2{編程

 

public static void main(String[] args) {數組

//只能輸入數字網絡

String str = "124354232";url

char[] arr = str.toCharArray();spa

boolean flag = true;orm

for(int i = 0 ;  i< arr.length ; i++){htm

if(!(arr[i]>=48&&arr[i]<=57)){

flag = false;

}

}

System.out.println(flag?"輸入正確":"輸出只能是數字");

}

 

 

}

使用正則表達式:

public class Demo2{

 

public static void main(String[] args) {

//只能輸入數字

String str = "12435423a2";

boolean flag = str.matches("[0-9]+");

System.out.println(flag?"輸入正確":"只能輸入數字");

 

}

}

 

1.2 正則表達式的符號

預約義字符類

.

任何字符(與行結束符可能匹配也可能不匹配)

 

\d

數字:[0-9]

 

\D

非數字: [^0-9]

 

\s

空白字符:[ \t\n\x0B\f\r]

 

\S

非空白字符:[^\s]

 

\w

單詞字符:[a-zA-Z_0-9]

 

\W

非單詞字符:[^\w]

 

System.out.println("a".matches("."));

System.out.println("1".matches("\\d"));

System.out.println("%".matches("\\D"));

System.out.println("\r".matches("\\s"));

System.out.println("^".matches("\\S"));

System.out.println("a".matches("\\w"));

 

Greedy 數量詞

X?

X,一次或一次也沒有

X*

X,零次或屢次

X+

X,一次或屢次

X{n}

X,剛好n

X{n,}

X,至少n

X{n,m}

X,至少n次,可是不超過m

System.out.println( "a".matches(".") );

System.out.println( "a".matches("a") );

System.out.println("a".matches("a?") );

System.out.println( "aaa".matches("a*") );

System.out.println( "".matches("a+") );

System.out.println( "aaaaa".matches("a{5}") );

System.out.println( "aaaaaaaaa".matches("a{5,8}") );

System.out.println( "aaa".matches("a{5,}") );

System.out.println( "aaaaab".matches("a{5,}") );

 

範圍表示

[abc]

ab c(簡單類)

[^abc]

任何字符,除了 ab c(否認)

[a-zA-Z]

a z A Z,兩頭的字母包括在內(範圍)

[a-d[m-p]]

a d m p[a-dm-p](並集)

[a-z&&[def]]

de f(交集)

[a-z&&[^bc]]

a z,除了 b c[ad-z](減去)

[a-z&&[^m-p]]

a z,而非 m p[a-lq-z](減去)

 

 

System.out.println( "a".matches("[a]") );

System.out.println( "aa".matches("[a]+") );

System.out.println( "abc".matches("[abc]{3,}") );

System.out.println( "abc".matches("[abc]+") );

System.out.println( "dshfshfu1".matches("[^abc]+") );

System.out.println( "abcdsaA".matches("[a-z]{5,}") );

System.out.println( "abcdsaA12".matches("[a-zA-Z]{5,}") );

System.out.println( "abcdsaA12".matches("[a-zA-Z0-9]{5,}") );

System.out.println( "abdxyz".matches("[a-c[x-z]]+"));

System.out.println( "bcbcbc".matches("[a-z&&[b-c]]{5,}"));

System.out.println( "tretrt".matches("[a-z&&[^b-c]]{5,}"));

 

 

1.3 匹配功能

需求:校驗QQ號,要求:必須是5~15位數字,0不能開頭。沒有正則表達式以前

public static void checkQQ(String qq)

{

int len = qq.length();

if(len>=5 && len <=15)

{

if(!qq.startsWith("0"))

{

try

{

long l = Long.parseLong(qq);

System.out.println("qq:"+l);

}

catch (NumberFormatException e)

{

System.out.println("出現非法字符");

}

}

else

System.out.println("不能夠0開頭");

}

else

System.out.println("QQ號長度錯誤");

}

有了正則表達式以後:

[1-9][0-9]{4,14}   [1-9]表示是第一位數字是會出現1-9範圍之間的其中一個,下來的數字範圍會出如今0-9之間,至少出現4次,最多出現14次。

public static void checkQQ2()         

{                                     

String qq = "12345";              

String reg = "[1-9][0-9]{4,14}";  

boolean b = qq.matches(reg);      

System.out.println("b="+b);                                 

}                                     

 

需求:匹配是否爲一個合法的手機號碼。

public static void checkTel()                                                   

{                                                                               

String tel = "25800001111";                                                 

String reg = "1[35]\\d{9}";//在字符串中,定義正則出現\ 要一對出現。         

boolean b= tel.matches(reg);                                                

System.out.println(tel+":"+b);                                              

}                                                                               

1.4 切割功能

需求1:根據空格對一段字符串進行切割。

public static void splitDemo()                              

{                                                           

String str = "aa.bb.cc";                                

str = "-1     99    4    23";                           

String[] arr = str.split(" +");                         

for(String s : arr)                                     

{                                                       

System.out.println(s);                              

}                                                       

}                                                           

需求2 :根據重疊詞進行切割。

public static void splitDemo2()        

{                                      

String str = "sdqqfgkkkhjppppkl";

String[] arr = str.split("(.)\\1+");

for(String s : arr)                

{                                  

System.out.println(s);         

}                                  

                                       

}                                      

注意:爲了提升規則複用,用()進行封裝,每個括號都有一個編號,從1開始,爲了複用這個規則。能夠經過編號來完成該規則的調用。須要對編號數字進行轉義。\\1就表明獲取1組規則。

1.5 替換功能

需求:把手機號替換成*」號。

String str = "聯繫我:13567012119聯繫我:13567012119聯繫我:13567012119聯繫我:13567012119聯繫我:13567012119聯繫我:13567012119";

String reg= "1[34578]\\d{9}";

str = str.replaceAll(reg,"******");

System.out.println("替換後的帖子:"+ str);

練習二:我我...........要要...要學....學學.....編編......

將字符串還原成  我要學編程。

 

 

1.6 獲取

獲取須要使用到正則的兩個對象:使用的是用正則對象Pattern 和匹配器Matcher

用法:

範例:

 Pattern p = Pattern.compile("a*b");

 Matcher m = p.matcher("aaaaab");

 boolean b = m.matches();

步驟:

1,先將正則表達式編譯成正則對象。使用的是Pattern類一個靜態的方法。compile(regex);

2,讓正則對象和要操做的字符串相關聯,經過matcher方法完成,並返回匹配器對象。

3,經過匹配器對象的方法將正則模式做用到字符串上對字符串進行鍼對性的功能操做

需求:獲取由3個字母組成的單詞。

public static void getDemo()

{

String str = "da jia zhu yi le,ming tian bu fang jia,xie xie!";

//想要獲取由3個字母組成的單詞。

//剛纔的功能返回的都是一個結果,只有split返回的是數組,可是它是把規則做爲分隔符,不會獲取符合規則的內容。

//這時咱們要用到一些正則對象。

String reg = "\\b[a-z]{3}\\b";

Pattern p = Pattern.compile(reg);

Matcher m = p.matcher(str);

while(m.find())

{

System.out.println(m.start()+"...."+m.end());

System.out.println("sub:"+str.substring(m.start(),m.end()));

System.out.println(m.group());

}

// System.out.println(m.find());//將規則對字符串進行匹配查找。

// System.out.println(m.find());//將規則對字符串進行匹配查找。

// System.out.println(m.group());//在使用group方法以前,必需要先找,找到了才能夠取。

}

練習3:校驗郵件

public static void checkMail()

{

String mail = "abc123@sina.com.cn";

mail = "1@1.1";

String reg = "[a-zA-Z_0-9]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";

reg = "\\w+@\\w+(\\.\\w+)+";//簡化的規則。籠統的匹配。

boolean b = mail.matches(reg);

System.out.println(mail+":"+b);

}

練習4:網絡爬蟲

class GetMailList

{

public static void main(String[] args) throws Exception

{

String reg = "\\w+@[a-zA-Z]+(\\.[a-zA-Z]+)+";

getMailsByWeb(reg);

}

 

 

public static void getMailsByWeb(String regex)throws Exception

{

URL url = new URL("http://localhost:8080/myweb/mail.html");

 

URLConnection conn = url.openConnection();

BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line = null;

Pattern p = Pattern.compile(regex);

while((line=bufIn.readLine())!=null)

{

//System.out.println(line);

Matcher m = p.matcher(line);

while(m.find())

{

System.out.println(m.group());

}

}

bufIn.close();

}

public static void getMails(String regex)throws Exception

{

BufferedReader bufr =

new BufferedReader(new FileReader("mail.txt"));

String line = null;

Pattern p = Pattern.compile(regex);

while((line=bufr.readLine())!=null)

{

//System.out.println(line);

Matcher m = p.matcher(line);

while(m.find())

{

System.out.println(m.group());

}

}

bufr.close();

}

}

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息