/*
* 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]);
}
}
}
}
输出结果: