言歸正傳:java中String類里面封裝了很多字符串處理的方法,替換、查找、包含等,但是我今天遇到了一個功能竟然沒有封裝,就是查找出字符串內所有匹配正則表達式的字符串數組,(源字符串“2012-08-12 水電費 2012-12 abcde 2012-08-23”,正則表達式:“\\d{4}[ /-]{1}\\d{2}([ /-]{1}\\d{2})?”,我所需要的就是{“2012-08-12”,“2012-12”,“2012-08-23”}),這該怎么實現呢?
為了實現我的目的,我也煞費周折啊。認真研究了Pattern和Matcher兩個類,幸好是,要不然我也就體會不到這種柳暗花明的感覺了,也感受不到正則的魅力了。其實String自身攜帶的方法已夠應付絕大多數的應用了,Pattern中的方法基本在String中都有體現,即單獨使用Pattern的時候相對就少了一點,Matcher也就使用了find() 和group()就可以實現我上面提出的功能了。
具體實現:
String str="2012-08-12 2012-12 abcde 2012-08-23 ";
String regex = "\\d{4}[ /-]{1}\\d{2}([ /-]{1}\\d{2})?"; //正則表達式
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(str);
List<String> matchRegexList = new ArrayList<String>();
while(m.find()){
matchRegexList.add(m.group());
}
下面是整個字符串通過正則表達式進行拆分后(包含拆分符,String.split()返回的不包含正則表達式的值,要不然我也不用費那么大勁了)的數組:
String str="2012-08-12 2012-12 abcde 2012-08-23 ";
String regex = "\\d{4}[ /-]{1}\\d{2}([ /-]{1}\\d{2})?"; //正則表達式
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(str);
List<String> matchRegexList = new ArrayList<String>();
while(m.find()){
matchRegexList.add(m.group());
}
System.out.println(m.groupCount());
String[] result = pattern.split(str); //使用正則表達式,分割字符串
List<String> allSplitList = new ArrayList<String>();
int len = matchRegexList.size() > result.length ? matchRegexList.size():result.length;
for(int i=0; i<len; i++){
if(i<result.length){
allSplitList.add(result[i]);
}
if(i<matchRegexList.size()){
allSplitList.add(matchRegexList.get(i));
}
}
for (int i = 0; i < allSplitList.size(); i++) { //獲取源字符串中匹配正則表達的字符串
System.out.println("-"+allSplitList.get(i)+"-");
}
