JAVA學習筆記之Regex__java

來源:互聯網
上載者:User

Regex(regular expression)描述的是一種字串匹配的模式,使字串更易於操作。但其弊端就是使代碼的閱讀性降低。
專門用於對字串的操作包括:
1、匹配
String類中提供了匹配的方法matches()
boolean matches(String regex) —->告知此字串是否匹配給定的Regex。
2、切割
String類中提供了切割的方法
String[] split(String regex) —->根據匹配給定的Regex來拆分此字串。
例如:

public class RegexDemo {    public static void main(String[] args) {        String str="123  48  489     330";        String[] s = str.split(" +");//規則:以空格符為分隔字元,輸出分隔字元之間的內容,X+指的是一次或多次出現的符號        for(String sps:s){        System.out.println(sps);        }    }    }

輸出
123
48
489
330
3、替換
String replaceAll(String regex, String replacement) —->使用給定的 replacement 替換此字串所有匹配給定的Regex的子字串。
例如:需求是將輸入的手機號中間四位輸出為*

public class RegexDemo {    public static void main(String[] args) {        String temp="15100004567";        String str=temp.replaceAll("(\\d{3})(\\d{4})(\\d{4})","$1****$3" );        //1、(A)將括弧內內容作為一個組,後面直接引用。        //2、X{n}+表示X出現恰好 n 次。        //3、如果有兩個字串,後面的字串取前一個字串的組時,要用$符號,$1表示取第一個組,也就是前三個數字,$3表示取第三個組,也就是最後四個數字        System.out.println(str);    }    }

輸出為151****4567。
練習:需要將輸入的字串中兩個以上出現的字元替換為空白符

public class RegexDemo {    public static void main(String[] args) {        String temp1="ad$$ddugj7777do8dk%%%dfg";        String str1=temp1.replaceAll("(.)\\1+"," " );//(.)意思就是將出現的任一字元封裝成一個組,\\1+的意思是前面出現的組要出現1次以上。綜上,匹配出來的就是一個多次出現的字元組合        System.out.println(str1);    }    }
輸出:ad  ugj do8dk dfg

4、擷取
實現擷取:將符合規則的內容取出來
用到Regex對象(java.util.regex)
1、將字串規則封裝成Pattern對象。compile(regex)方法
2、通過正則對象擷取匹配器對象,用到將正則規則作用到要操作的字串上
3、通過匹配器對象的方法,對字串進行操作
樣本:

 Pattern p = Pattern.compile("a*b");//將規則編譯成對象 Matcher m = p.matcher("aaaaab");//和要操作的字串關聯,產生匹配器對象 boolean b = m.matches();//使用匹配對象方法對字串操作

練習:需求是取出字串中由三個字母組成的單詞“abc hd haha zsy shi hdu le hyssd”

import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexGet {    public static void main(String[] args) {        String temp = "abc hd haha zsy shi hdu  le hyssd";        String regex="\\b[a-zA-Z]{3}\\b";//\b是指單詞的邊界,該規則的意思是尋找單詞字母個數為3的 ;如果只是單純得將規則定為[a-zA-Z]{3},輸出就會出現錯誤,例如出現hah這樣的結果。          Pattern p = Pattern.compile(regex);         Matcher m = p.matcher(temp);        while(m.find()){ //find()方法是判斷有無匹配到的字串,傳回值為boollean,該迴圈與迭代器類似             String g = m.group();//group()方法是抓取匹配到的字串             System.out.println(g);         }    }}

輸出為
abc
zsy
shi
hdu

聯繫我們

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