java:Regex

來源:互聯網
上載者:User

標籤:pil   bsp   cep   static   void   stack   一個   end   pattern   

* 字串支援Regex的方法
* matches(String regex):將字串與指定的Regex進行匹配,匹配成功返回true,否則返回false
*
* 電話號碼的校正:3為區號+8位電話號碼 4位區號+7位電話號碼
* 010-12345678(01012345678) 021-12345678 027-12345678 029-12345678....
* 0371-1234567(03711234567)
* 網址校正:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
* http://www.baidu.com
* http://www.baidu.com/index.html

public class TestVertify2 {    /**     * 校正電話號碼     * @param tel     */    public static boolean checkTel(String tel){//        String regex="\\d{3,4}-?\\d{7,8}";        String regex="((0[12]\\d{1})-?\\d{8})|(0\\d{3})-?\\d{7}";        return tel.matches(regex);    }    /**     * 校正網址:http://www.baidu.com     * @param url     * @return     */    public static boolean checkURL(String url){        String regex="http://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";        return url.matches(regex);    }        /**     * 校正QQ號碼     * @param qq     * @return     */    public static boolean checkQQ(String qq){        String regex="[1-9]\\d{4,14}";        return qq.matches(regex);            }    public static void main(String[] args) {//        boolean is = checkTel("021-12345678");        boolean is = checkURL("http://www.baidu.com/index.html");        System.out.println(is);    }}

* 字串中支援Regex的常用方法:
* ***matches(String regex):將字串與指定的Regex進行匹配,匹配成功返回true,否則返回false
* **replaceAll(String regex, String replacement)
* 使用給定的 replacement 替換此字串所有匹配給定的Regex的子字串。
* replaceFirst(String regex, String replacement)
* 使用給定的 replacement 替換此字串匹配給定的Regex的第一個子字串。
* split(String regex)
* 根據給定Regex的匹配拆分此字串。

public class TestString {    public static void testReplace(){        String str="我是張三,我的QQ:12345,我的電話是:0371-1234567";        String regex="\\d+";//        str = str.replaceAll(regex, "#");        str = str.replaceFirst(regex, "#");        System.out.println(str);    }        public static void testSplit(){        String str="java,html,,oracle,,,mysql,,,,javascript";        String regex=",+";//可以匹配一次或多次逗號        String[] strs = str.split(regex);        for (String string : strs) {            System.out.println(string);        }    }    public static void main(String[] args) {        testSplit();    }}

*ava.util.regex 包主要包括以下二個類:
Pattern 類:
pattern 對象是一個Regex的編譯表示。
Pattern 類沒有公用構造方法。要建立一個 Pattern 對象,
你必須首先調用其公用靜態編譯方法,它返回一個 Pattern 對象。該方法接受一個Regex作為它的第一個參數。
常用的方法:
compile(String regex) 將給定的Regex編譯到模式中。
matches(String regex, CharSequence input) 編譯給定Regex並嘗試將給定輸入與其匹配。
matcher(CharSequence input) 建立匹配給定輸入與此模式的匹配器。
Matcher 類:
Matcher 對象是對輸入字串進行解釋和匹配操作的引擎。
與Pattern 類一樣,Matcher 也沒有公用構造方法。
你需要調用 Pattern 對象的 matcher 方法來獲得一個 Matcher 對象。
常用方法:
find() 嘗試尋找與該模式比對的輸入序列的下一個子序列。

public class TestRegex {    public static void testPattern(){        String content="bjsxt java is good school!";        String regex = ".*java.*";        boolean isMatcher= Pattern.matches(regex, content);        System.out.println("是否包含‘java‘子字串:"+isMatcher);    }        public static void testMatches(){          String line = "This order was placed for QT3000! OK?";          String regex = "(\\D*)(\\d+)(.*)";              //1.建立Pattern對象          Pattern pattern = Pattern.compile(regex);          //2.建立Mather對象          Matcher matcher=pattern.matcher(line);          if(matcher.find()){             System.out.println("第一組:"+matcher.group(0));             System.out.println("第二組:"+matcher.group(1));             System.out.println("第三組:"+matcher.group(2));             System.out.println("第四組:"+matcher.group(3));          }    }        public static void main(String[] args) {//        testPattern();        testMatches();    }}

eg:

*網路爬蟲:將網易首頁源碼上的超級連結提取出來。
*1.擷取網頁首頁的源碼
*2.使用Regex進行匹配源碼,將超級連結提取

public class WebSipder {    public static void main(String[] args) {        try {            //擷取網易源碼            URL url = new URL("http://www.163.com");            InputStream ips = url.openStream();            InputStreamReader isr = new InputStreamReader(ips);            BufferedReader br = new BufferedReader(isr);            StringBuilder sb = new StringBuilder();            String str;            while((str=br.readLine())!=null){                sb.append(str+"\n");            }//            System.out.println(sb);            //從源碼中提取網址 http://yuedu.163.com            String regex="http://\\w*\\.*\\w*\\.com";            //建立一個pattern對象(Regex)            Pattern pattern = Pattern.compile(regex);            Matcher matcher = pattern.matcher(sb);            while(matcher.find()){                String address = matcher.group();                System.out.println(address);            }            br.close();        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }            }}

 

java:Regex

聯繫我們

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