簡體   English   中英

檢查String是否僅包含這些字符{([])}

[英]Check if String only contains these characters {([])}

我正在嘗試編寫一個方法來檢查給定的字符串是否包含這些{([])}個字符。

// Test strings
String S = "{U}"  // should give FALSE
String S = "[U]"  // should give FALSE
String S = "U"  // should give FALSE
String S = "([)()]" // should give TRUE

我試過了:

    if(S.matches("[{(\\[\\])}]")) {
        return 1;
    }

但這種回歸永遠不會成真。

String.matches()整個字符串與模式匹配。 您正在嘗試的模式失敗,因為它只匹配單個字符 - 例如, "{".matches("[{(\\\\[\\\\])}]")將返回true。 你需要為正則表達式添加一個重復 - 如果你想匹配空字符串,則為*如果字符串必須包含至少一個字符,則為+ ,如下所示:

if(S.matches("[{(\\[\\])}]+")) {
    return 1;
}
if(S.matches("^[{(\\[\\])}]+$")) {
    return 1;
}

^ - 行的開頭

[]+ - 字符類[]包含的字符一次或多次

$ - 結束


如果你想創建一個方法 (正如你剛才提到的那樣),你可能要考慮創建這樣的方法返回boolean (注意返回booleantruefalse )不等於在Java中返回10 ):

public boolean checkIfContainsOnlyParenthesis(String input) {
    return input.matches("^[{(\\[\\])}]+$");
}

如果你的意圖是在條件滿足時返回1並且 - 例如 - 0 ,當它不是時,你需要將該方法的返回值更改為int

public int checkIfContainsOnlyParenthesis(String input) {
    if(input.matches("^[{(\\[\\])}]+$")) {
        return 1;
    } else {
        return 0;
    }
}

這樣你可以傳遞你的S字符串作為該方法的參數,如下所示:

checkIfContainsOnlyParenthesis(S);

暫無
暫無

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

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