I have been trying to figure out a REGEX expressions which can filter characters which are not '-' or 0-9. This expression will be used with a document filter which will filter characters being inserted into JTextFields. Let me explain in more detail...
When a user enters a character into a JTextField a DocumentFilter checks the input using the 'insertString' method in the DocumentFilter class. Because the method is called every time a character is inserted the REGEX needed to be able to handle parts of an integer as the user builds the string. For example,
Key Press 1): Value = '-' PASS
Key Press 2): Value = '-1' PASS
Key Press 3): Value = '-10' PASS etc...
However the filter should not allow the combination '-0' or '--' and should pass the following cases,
Negative Symbol Only ('-')
Negative Number Without Zero Next To '-' ('-01' fail)
Positive Values (0122 and 122 pass)
Here is my code:
package regex;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class CustomFilter extends DocumentFilter {
private String regex = "((-?)([1-9]??))(\d)";
/**
* Called every time a new character is added.
*/
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
String text = fb.getDocument().getText(0, fb.getDocument().getLength());
text += string;
if(text.matches(regex)) {
super.insertString(fb, offset, string, attr);
}
}
/**
* Called when the user pastes in new text.
*/
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String string = fb.getDocument().getText(0, fb.getDocument().getLength());
string += text;
if(string.matches(regex)) {
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
super.remove(fb, offset, length); // I may modify this later
}
}
If you believe I am going about this in the wrong direction please let me know. I am open to a more simplistic option.
Aucun commentaire:
Enregistrer un commentaire