match-function中的正则表达式在较大的if语句中不起作用

时间:2014-02-25 20:23:47

标签: java regex if-statement

我正在尝试检查我的Java应用程序中的设置是否设置不正确或缺失。由于我有一些设置,我有一个更长的if语句,包括一些带有正则表达式模式的String.match()函数。 但是,当我将所有这些语句组合在一起时,它只在一种情况下无法正常工作。如果我在多个语句中拆分语句就可以了。

这是我的代码:

// useResource and useCode are boolean, all other variables are Strings

if (
    ( useResource && resourceName.isEmpty() )
    || username.isEmpty()
    || password.isEmpty()
    || !serverURL.matches("^[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)?(/.+)?")
    || !serverURL.matches("^([0-9]{1,3}\\.){3}[0-9]{1,3}(/.+)?")
    || serverURL.matches("/$")
    || (useCode && !code.matches("[0-1]{5}"))
)
{
    return true;
} else {
    return false;
}

serverURL 变量上使用的正则表达式模式应检查内容是否类似于DNS名称(www.example1.com,www.sub.example2.com,www.example1.com /。 ..,www.sub.example2.com / ...)或IP(192.168.0.1或192.168.0.1 / ...)并且它不应以斜杠结尾。

总之:如果某些设置未设置或设置不正确,我希望该函数返回true。

就像我已经提到的那样,该功能有效,除非变量 serverURL 包含DNS名称。然后我总是弄错了。但是,当我使用如下所示的构造时,它可以工作:

int settingsMissing = 0;

if (useResource && resourceName.isEmpty())
    settingsMissing++;

if (username.isEmpty())
    settingsMissing++;

if (password.isEmpty())
    settingsMissing++;

if (!serverURL.matches("^[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)?(/.+)?"))
    settingsMissing++;

if (!serverURL.matches("^([0-9]{1,3}\\.){3}[0-9]{1,3}(/.+)?"))
    settingsMissing++;

if (serverURL.matches("/$"))
    settingsMissing++;

if (useCode && !code.matches("[0-1]{5}"))
    settingsMissing++;

if (settingsMissing > 1 /*greater 1 because it can only a be DNS Name or an IP address*/ ) {
    return true;
} else {
    return false;
}

我是否想念Java中的大型if语句?

2 个答案:

答案 0 :(得分:0)

尝试使用模式匹配器获取与java中的regex相关的内容。

例如:

String URL =// things to be compared with the regex 

Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);

if (matcher.find()) {
   System.out.println("Found");
} else {
   System.out.println("Match not found");
}

答案 1 :(得分:0)

我认为我发现了问题,但还没有测试过。看来,我犯了一个逻辑错误。 IP地址不会导致 true 返回,因为它匹配两种正则表达式模式,但DNS名称只匹配为DNS名称设计的正则表达式模式而不是为IP地址设计的模式,因此它总是会导致 true 。我想我必须将这两种模式结合起来:

if ( [...]
   || (
       !serverURL.matches("^[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)?(/.+)?")
       &&
       !serverURL.matches("^([0-9]{1,3}\\.){3}[0-9]{1,3}(/.+)?")
      )
   || [...] )
{ [...] }

对不起,如果我浪费你的时间。