簡體   English   中英

匹配功能中的正則表達式在較大的if語句中不起作用

[英]regex in match-function doesn't work in bigger 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語句無法正常工作?

嘗試將PatternMatcher用於與Java中的正則表達式相關的事情。

例如:

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");
}

我想我找到了問題,但是還沒有測試。 看來,我犯了一個邏輯錯誤。 IP地址不會導致真實的返回,因為它與兩個正則表達式模式都匹配,但是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}(/.+)?")
      )
   || [...] )
{ [...] }

對不起,如果我浪費你的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM