1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.DefaultFormatter;
public class RegexFormatter extends DefaultFormatter {
private Pattern pattern;
/**
*
*/
public RegexFormatter() {
super();
// TODO Auto-generated constructor stub
}
public RegexFormatter(String pattern) {
super();
this.pattern = Pattern.compile(pattern);
// TODO Auto-generated constructor stub
}
public Object stringToValue(String text) throws ParseException {
Pattern pattern = getPattern();
if (pattern != null) {
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
return super.stringToValue(text);
}
throw new ParseException("Pattern did not match", 0);
}
return text;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = Pattern.compile(pattern);
}
} |
Partager