此篇文章是記錄我在學(xué)習(xí)Java正則表達(dá)式時(shí)候?qū)W到的和遇到的坑。
先來(lái)說說 Matcher 里面的三個(gè)方法(取的結(jié)果以group()方法為例子)
好了上測(cè)試代碼:
package com.wjj.utils;import java.util.regex.Matcher;import java.util.regex.Pattern;/*** @author 作者 : 榨菜哥* @version 創(chuàng)建時(shí)間:2016年8月18日 上午8:47:58* 類說明:正則表達(dá)式的練習(xí)*/public class Regex { //find方法測(cè)試 public static void find(String html) { String regex = "http://d//d//d"; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(html); System.out.print("find():"); if (matcher.find()) { System.out.println(matcher.group()); } } //matches方法測(cè)試 public static void matches(String html) { String regex = "^//w//d//d//d"; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(html); System.out.print("matches():"); if (matcher.matches()) { System.out.println(matcher.group()); } } //lookingAt方法測(cè)試 public static void lookingAt(String html) { String regex = "http://w//d//d"; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(html); System.out.print("lookingAt():"); if (matcher.lookingAt()) { System.out.println(matcher.group()); } } public static void main(String[] args) { //find方法測(cè)試 find("a123b"); //matches方法測(cè)試 matches("a123"); //lookingAt方法測(cè)試 lookingAt("a123b"); }}
輸出結(jié)果:
find():123
matches():a123
lookingAt():a12
小結(jié):正則表達(dá)式本身并不難,平常使用的時(shí)候只要按照規(guī)則來(lái)寫就好了。在學(xué)習(xí)中理解matches、find、和lookingAt三個(gè)方法花了我比較長(zhǎng)的時(shí)間,一直不能理解完全匹配和部分匹配是什么意思,最后還是在stackoverflow上找到了想要的答案。
以上是個(gè)人學(xué)習(xí)的理解,有不對(duì)之處,希望給予指點(diǎn)。
(補(bǔ)充:正則表達(dá)式Pattern如果調(diào)用多次容易出問題,比如內(nèi)存溢出,因?yàn)镻attern每執(zhí)行一次就編譯一次正則表達(dá)式,因此建議將需要的正則表達(dá)式進(jìn)行預(yù)編譯。)
正則表達(dá)式學(xué)習(xí)教程: http://deerchao.net/tutorials/regex/regex.htm ,文中作者寫得挺詳細(xì)的,并且通俗易懂。
總結(jié)
以上所述是小編給大家介紹的Java正則相關(guān)的Pattern和Matcher類及遇到的坑,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
新聞熱點(diǎn)
疑難解答