一个简化java.util.regex.*使用的类

/*
 * PatternMatcher.java
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies.
 *
 * ALSAN WONG MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. ALSAN WONG
 * SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT
 * OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 * 
 * Created on 2005-6-13
 * Copyright 2005, alsan.home.net
 
*/
package net.alsan.jlib.util;

import java.util.ArrayList;
import java.util.regex.
*;

/**
 * 
 * @author alsan
 * @version 1.0
 
*/
public final class PatternMatcher {
    
private final Pattern pattern;
    
public Matcher matcher;

    
public PatternMatcher(String sPattern) {
        pattern 
= Pattern.compile(sPattern);
    }

    
public boolean match(String content) {
        
return (matcher = pattern.matcher(content)).find();
    }

    
public ArrayList getMatchesList() {
        ArrayList matches 
= new ArrayList();

        
do {
            ArrayList groups 
= new ArrayList();

            
for (int i = 0, cnt = matcher.groupCount(); i < cnt; i++) {
                groups.add(matcher.group(i 
+ 1));
            }

            matches.add(groups);
        } 
while (matcher.find());

        
return matches;
    }

    
public String[][] getMatches() {
        ArrayList list 
= getMatchesList();
        String[][] matches 
= new String[list.size()][];

        
for (int i = 0; i < matches.length; i++) {
            ArrayList groups 
= (ArrayList) list.get(i);
            matches[i] 
= new String[groups.size()];

            
for (int j = 0; j < matches[i].length; j++) {
                matches[i][j] 
= (String) groups.get(j);
            }
        }

        
return matches;
    }
}

测试代码:

    public static void main(String[] args) {
        final PatternMatcher regex 
= new PatternMatcher("(\\d{2,4}-\\d{1,2}-\\d{1,2})");

        
if (regex.match("05-1-10,100;2005-01-11,1000")) {
            String[][] matches 
= regex.getMatches();

            
for (int i = 0; i < matches.length; i++) {
                
for (int j = 0; j < matches[i].length; j++) {
                    System.
out.println(matches[i][j]);
                }
            }
        }
    }

输出结果:

05-1-10
2005-01-11

posted on 2005-06-13 17:12 毒菇求Buy 阅读(310) 评论(0)  编辑 收藏 引用 所属分类: JAVARegex

只有注册用户登录后才能发表评论。
<2005年6月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

导航

统计

常用链接

留言簿(7)

随笔分类(133)

随笔档案(111)

文章分类(65)

文章档案(53)

相册

收藏夹(30)

BLOG

Book store

Graphics Design

搜索

最新评论

阅读排行榜

评论排行榜