正則表達(dá)式作為Perl最出眾的賣點,已經(jīng)在Linux平臺上廣泛的應(yīng)用,比如命令grep sed等。JDK1.4 在NIO中重要提供了正則表達(dá)式引擎的實現(xiàn)。本系列將通過解決問題的方式來深入學(xué)習(xí)Java正則表達(dá)式。
最終我們目標(biāo)是如何通過正則表達(dá)式獲取Java代碼中方法的個數(shù)與屬性的個數(shù)(當(dāng)然通過反射是小Case)
(1)如何統(tǒng)計一行中重復(fù)單詞
如果沒有正則表達(dá)式,我們只能解析逐個判斷了。正則呢?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
*
* @author vma
*/
public class MatchDuplicateWords {
public static void main(String args[]){
hasDuplicate("Faster pussycat haha haha dd dd haha haha zz zz");
}
public static boolean hasDuplicate(String phrase){
boolean retval=false;
String duplicatePattern ="\\b(\\w+) \\1\\b";
Pattern p = null;
try{
p = Pattern.compile(duplicatePattern);
}
catch (PatternSyntaxException pex){
pex.printStackTrace();
System.exit(0);
}
//count the number of matches.
int matches = 0;
//get the matcher
Matcher m = p.matcher(phrase);
String val=null;
//find all matching Strings
while (m.find()){
retval = true;
val = ":" + m.group() +":";
System.out.println(val);
matches++;
}
//prepare a message indicating success or failure
String msg = " NO MATCH: pattern:" + phrase
+ "\r\n regex: "
+ duplicatePattern;
if (retval){
msg = " MATCH : pattern:" + phrase
+ "\r\n regex: "
+ duplicatePattern;
}
System.out.println(msg +"\r\n");
return retval;
}
}