DocumentFilter的正则表达式匹配所有十进制数,但最后只有一个小数
问题首先 :我需要正则表达式匹配
111
或111.
或111.111
(只是aritrarty数字)为DocumentFilter
。 我需要用户能够输入111.
带decimal
,之后没有任何内容。 似乎无法做对。
我找到的所有正则表达式都只匹配所有十进制数字即
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
或111.
或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(); } }); } }
编辑:
我最初的假设是传递给方法的str
是整个文档String,所以我很困惑为什么答案不起作用。 我意识到它只是传递的String的插入部分。
也就是说,如果从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); }
以下正则表达式可能适合您:
^[0-9]+[.]?[0-9]{0,}$
量词{0,}
将匹配零个或多个数字。
我会使用正则表达式
^\d+\.?\d*$
这里的解释和演示: http : //regex101.com/r/iM3nX5
确保双重转义转义序列,如下所示:
Pattern regEx = Pattern.compile("^\\d+\\.?\\d*$");