001 /*
002 * Cobertura - http://cobertura.sourceforge.net/
003 *
004 * Copyright (C) 2005 Mark Doliner
005 * Copyright (C) 2006 John Lewis
006 *
007 * Note: This file is dual licensed under the GPL and the Apache
008 * Source License (so that it can be used from both the main
009 * Cobertura classes and the ant tasks).
010 *
011 * Cobertura is free software; you can redistribute it and/or modify
012 * it under the terms of the GNU General Public License as published
013 * by the Free Software Foundation; either version 2 of the License,
014 * or (at your option) any later version.
015 *
016 * Cobertura is distributed in the hope that it will be useful, but
017 * WITHOUT ANY WARRANTY; without even the implied warranty of
018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
019 * General Public License for more details.
020 *
021 * You should have received a copy of the GNU General Public License
022 * along with Cobertura; if not, write to the Free Software
023 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
024 * USA
025 */
026
027 package net.sourceforge.cobertura.util;
028
029 import java.util.Collection;
030 import java.util.Iterator;
031
032 import org.apache.log4j.Logger;
033 import org.apache.oro.text.regex.MalformedPatternException;
034 import org.apache.oro.text.regex.Pattern;
035 import org.apache.oro.text.regex.Perl5Compiler;
036 import org.apache.oro.text.regex.Perl5Matcher;
037
038 /**
039 * Abstract, not to be instantiated utility class for Regex functions.
040 *
041 * @author John Lewis (logic copied from MethodInstrumenter)
042 */
043 public abstract class RegexUtil
044 {
045
046 private static final Logger logger = Logger.getLogger(RegexUtil.class);
047
048 private final static Perl5Matcher pm = new Perl5Matcher();
049
050 /**
051 * <p>
052 * Check to see if one of the regular expressions in a collection match
053 * an input string.
054 * </p>
055 *
056 * @param regexs The collection of regular expressions.
057 * @param str The string to check for a match.
058 * @return True if a match is found.
059 */
060 public static boolean matches(Collection regexs, String str)
061 {
062 Iterator iter = regexs.iterator();
063 while (iter.hasNext())
064 {
065 Pattern regex = (Pattern)iter.next();
066 if (pm.matches(str, regex))
067 {
068 return true;
069 }
070 }
071
072 return false;
073 }
074
075 public static void addRegex(Collection list, String regex)
076 {
077 try
078 {
079 Perl5Compiler pc = new Perl5Compiler();
080 Pattern pattern = pc.compile(regex);
081 list.add(pattern);
082 }
083 catch (MalformedPatternException e)
084 {
085 logger.warn("The regular expression " + regex + " is invalid: "
086 + e.getLocalizedMessage());
087 }
088 }
089
090 }