📄 wildcardmatcher.java
字号:
package org.mandarax.util.regex;
/*
* Copyright (C) 1999-2004 <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</a>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.util.regex.*;
/**
* An utility to match string containing wild cards.
* @author <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</A>
* @version 3.4 <7 March 05>
* @since 3.0
*/
public class WildcardMatcher {
private char SOME = '%';
private char ONE = '_';
private char ESC = '\\';
public static final WildcardMatcher DB_INSTANCE = new WildcardMatcher('%','_','\\');
public static final WildcardMatcher FILE_INSTANCE = new WildcardMatcher('*','?','\\');
/**
* Constructor.
* @param some the character representing a sequence of characters
* @param one the character representing one character
* @param esc the character used to unmark special characters
*/
public WildcardMatcher(char some,char one,char esc) {
super();
SOME = some;
ONE = one;
ESC = esc;
}
/**
* Matches a string and a pattern containing wildcards.
* @param pattern a pattern string
* @param string the string to be tested
* @return a boolean
*/
public boolean matches(String pattern,String string) {
if (string==null || pattern==null) return true;
Pattern p = getPattern(pattern);
Matcher m = p.matcher(string);
return m.matches();
}
/**
* Get the RegEx pattern for the respective string with wild cards.
* @param pattern a pattern string
* @return a RegEx pattern instance
*/
public Pattern getPattern(String pattern) {
String regExDef = replace(pattern,SOME,".*");
regExDef = replace(regExDef,ONE,".");
return Pattern.compile(regExDef);
}
/**
* Utility to replace sub strings by patterns.
* @param text a string
* @param old the old text
* @param replacement the text replacing the old text
* @return the result of the replacement
*/
public String replace(String text,char old,String replacement) {
StringBuffer buf = new StringBuffer();
for (int i=0;i<text.length();i++) {
char c = text.charAt(i);
if (c==old) {
if (i>0 && buf.charAt(i-1)==ESC) buf.append(c);
else buf.append(replacement);
}
else buf.append(c);
}
return buf.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -