正則表達式作為Perl最出眾的賣點,已經在Linux平臺上廣泛的應用,比如命令grep sed等。JDK1.4 在NIO中重要提供了正則表達式引擎的實現。本系列將通過解決問題的方式來深入學習Java正則表達式。
最終我們目標是如何通過正則表達式獲取Java代碼中方法的個數與屬性的個數(當然通過反射是小Case)
(1)如何統計一行中重復單詞
如果沒有正則表達式,我們只能解析逐個判斷了。正則呢?
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;
}
}