先问问题:我需要正则表达式来匹配111
or 111.
or 111.111
(只是任意数字)DocumentFilter
。我需要用户能够输入111.
with a decimal
之后什么也没有。似乎无法正确处理。
我发现所有正则表达式都匹配all小数,即
12343.5565
32.434
32
就像这个正则表达式
^[0-9]*(\\.)?[0-9]+$
问题是,我需要正则表达式DocumentFilter
因此输入只能是带/不带小数点的数字。但问题是它也需要匹配
1223.
因此用户可以在文本字段中输入小数。所以基本上我需要正则表达式来匹配
11111 // all integer
11111. // all integers with one decimal point and nothing after
11111.1111 // all decimal numbers
到目前为止我所拥有的模式就是上面的模式。这是一个测试程序(对于Java用户)
可以在这一行输入模式
Pattern regEx = Pattern.compile("^[0-9]*(\\.)?[0-9]+$");
如果正则表达式符合要求,那么您将能够输入111
or 111.
or 111.111
.
运行 :)
import java.awt.GridBagLayout;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.text.*;
public class DocumentFilterRegex {
JTextField field = new JTextField(20);
public DocumentFilterRegex() {
((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() {
Pattern regEx = Pattern.compile("^[0-9]*(\\.)?[0-9]+$");
@Override
public void insertString(DocumentFilter.FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException {
Matcher matcher = regEx.matcher(str);
if (!matcher.matches()) {
return;
}
super.insertString(fb, off, str, attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException {
Matcher matcher = regEx.matcher(str);
if (!matcher.matches()) {
return;
}
super.replace(fb, off, len, str, attr);
}
});
JFrame frame = new JFrame("Regex Filter");
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DocumentFilterRegex();
}
});
}
}
EDIT:
我最初的假设是str
传递给方法的是整个文档字符串,所以我对为什么答案不起作用感到困惑。我意识到这只是传递的字符串的尝试插入部分。
也就是说,如果您从 FilterBypass 获取整个文档字符串并根据整个文档字符串检查正则表达式,那么答案就很完美。就像是
@Override
public void insertString(DocumentFilter.FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException {
String text = fb.getDocument().getText(0, fb.getDocument().getLength() - 1);
Matcher matcher = regEx.matcher(text);
if (!matcher.matches()) {
return;
}
super.insertString(fb, off, str, attr);
}