Java中正則Matcher類的matches()、lookAt()和find()的差別

來源:互聯網
上載者:User

標籤:http   star   序列   div   com   test   false   group   fresh   

參考博文地址:http://www.oseye.net/user/kevin/blog/170

1、matcher():僅僅有在整個字串全然匹配才返回true,否則返回false。

可是假設部分匹配成功。匹配的位置將移動到下次匹配的位置

2、lookingAt():總是從第一個字元開始匹配。不管匹配成功與否,都不會再繼續向下匹配

3、find():部分匹配,假設匹配成功。返回true,匹配的位置移動到下次匹配的位置。

package com.qunar.fresh.junweiyu.Test;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Test_regx {    public static void main(String[] args){        Pattern pattern = Pattern.compile("\\d{3,5}");        String s = "123-34345-234-00";        Matcher matcher = pattern.matcher(s);        /*matches:整個匹配,僅僅有整個字元序列全然匹配成功,才返回True,否則返回False。

但假設前部分匹配成功,將移動下次匹配的位置*/ System.out.println(matcher.matches()); /*false*/ /*測試匹配的位置*/ matcher.find(); System.out.println(matcher.start()); /*4*/ /*重設匹配的位置*/ matcher.reset(); /*find:部分匹配,從當前位置開始匹配,找到一個匹配的子串,將移動下次匹配的位置*/ System.out.println(matcher.find());/*true*/ System.out.println(matcher.group() + "---" + matcher.start());/*123---0*/ System.out.println(matcher.find());/*true*/ System.out.println(matcher.group() + "---" + matcher.start());/*34345---4*/ /*lookingAt:部分匹配。總是從第一個字元進行匹配,匹配成功了不再繼續匹配。匹配失敗了,也不繼續匹配。

*/ System.out.println(matcher.lookingAt());/*true*/ System.out.println(matcher.group() + "---" + matcher.start());/*123---0*/ System.out.println(matcher.lookingAt());/*true*/ System.out.println(matcher.group() + "---" + matcher.start());/*123-0*/ }}



Java中正則Matcher類的matches()、lookAt()和find()的差別

聯繫我們

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