gpt4 book ai didi

java - 实时验证 JTextField 的输入

转载 作者:太空宇宙 更新时间:2023-11-04 14:05:56 25 4
gpt4 key购买 nike

我有一个用于请求防火墙访问的表单(JTable)。对于用户要在其中输入源的 JTextField,我想在用户键入时实时验证输入。有效的输入将以绿色突出显示。无效不应被允许。

以下正则表达式是有效输入:

private static final String IP_Address = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\d";//56.1.2.3
private static final String IP_WithMask = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s+[255])(\\d{1,3}.){3}(\\d{1,3})"; //56.1.2.3 255.255.255.254
private static final String IP_CIDR = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s*/)(\\d{1,3})"; //56.1.2.3/24
private static final String IP_ADDRESS_Dash_Numeric_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*-)(\\d{1,3}))";// 56.1.2.3-4
private static final String IP_ADDRESS_Dash_ADDRESS_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*-\\s*)(\\d{1,3}.){3}(\\d{1,3}))";//56.1.2.3-56.1.2.5
private static final String IP_ADDRESS_To_Numeric_RANGE = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s*[T|t][O|o]\\s*)(\\d{1,3})";//56.1.2.3 to 255
private static final String IP_ADDRESS_To_ADDRESS_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*[T|t][O|o]\\s*)(\\d{1,3}.){3}(\\d{1,3}))";//56.1.2.3 to 56.1.3.5

在 JTextField 中,用户可以键入这些的任意排列。我需要识别/验证每种类型以便稍后对它们采取行动。

我正在使用

public class MyVerifyer extends InputVerifier{}

并将其应用到我的 JTextfield:

setInputVerifier();

问题:1. 有人能给我一个可以捕获所有这些情况的正则表达式吗?2. 如何在有人打字时实时匹配。也许将 TextListener 附加到 JTextField?

如果需要,我可以提供更多代码。

最佳答案

我认为你需要尝试这样的事情(未经测试):

private static final String IP_Address = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\d";//56.1.2.3
private static final String IP_WithMask = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s+[255])(\\d{1,3}.){3}(\\d{1,3})"; //56.1.2.3 255.255.255.254
private static final String IP_CIDR = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s*/)(\\d{1,3})"; //56.1.2.3/24
private static final String IP_ADDRESS_Dash_Numeric_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*-)(\\d{1,3}))";// 56.1.2.3-4
private static final String IP_ADDRESS_Dash_ADDRESS_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*-\\s*)(\\d{1,3}.){3}(\\d{1,3}))";//56.1.2.3-56.1.2.5
private static final String IP_ADDRESS_To_Numeric_RANGE = "(\\d{1,3}.){3}(\\d{1,3})(?:\\s*[T|t][O|o]\\s*)(\\d{1,3})";//56.1.2.3 to 255
private static final String IP_ADDRESS_To_ADDRESS_RANGE = "((\\d{1,3}.){3}(\\d{1,3})(?:\\s*[T|t][O|o]\\s*)(\\d{1,3}.){3}(\\d{1,3}))";//56.1.2.3 to 56.1.3.5

private static String regex_array = IP_Address + "|" + IP_WithMask + "|" + IP_CIDR + "|" + IP_ADDRESS_Dash_Numeric_RANGE + "|" + IP_ADDRESS_Dash_ADDRESS_RANGE + "|" + IP_ADDRESS_To_Numeric_RANGE + "|" + IP_ADDRESS_To_ADDRESS_RANGE;

public class MyInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText().trim();
if (text.isEmpty()) return false;
if (text.matches(regex_array)) return false;

return true;
}

关于java - 实时验证 JTextField 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28866385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com