Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created January 14, 2022 03:34
Show Gist options
  • Save RustyKnight/3318d35484e90474373cd4b32c4dd72c to your computer and use it in GitHub Desktop.
Save RustyKnight/3318d35484e90474373cd4b32c4dd72c to your computer and use it in GitHub Desktop.
A document filter which can support a regular expression
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class RegularExpressionDocumentFilter extends ChainedDocumentFilter {
// Useful for every kind of input validation !
// this is the insert pattern
// The pattern must contain all subpatterns so we can enter characters into a text component !
private Pattern pattern;
public RegularExpressionDocumentFilter(DocumentFilter filter, Pattern pattern) {
super(filter);
this.pattern = pattern;
}
public RegularExpressionDocumentFilter(Pattern p) {
this(null, p);
}
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
String newStr = fb.getDocument().getText(0, fb.getDocument().getLength()) + string;
Matcher m = pattern.matcher(newStr);
if (m.matches()) {
super.insertString(fb, offset, string, attr);
} else {
}
}
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment