简体   繁体   English

检查String是否仅包含这些字符{([])}

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

I'm trying to write a method that checks if a given 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

I've tried: 我试过了:

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

But this returns never true. 但这种回归永远不会成真。

String.matches() matches the entire string against the pattern. String.matches()整个字符串与模式匹配。 The pattern you are trying is failing because it only matches a single character - for example, "{".matches("[{(\\\\[\\\\])}]") would return true. 您正在尝试的模式失败,因为它只匹配单个字符 - 例如, "{".matches("[{(\\\\[\\\\])}]")将返回true。 You need to add a repeat to your regex - either * if you want to match empty strings, or + if the string must contain at least one character, like so: 你需要为正则表达式添加一个重复 - 如果你想匹配空字符串,则为*如果字符串必须包含至少一个字符,则为+ ,如下所示:

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

^ - beginning of the line ^ - 行的开头

[]+ - characters contained in character class [] ONE OR MORE times []+ - 字符类[]包含的字符一次或多次

$ - end of the line $ - 结束


If you want to create a method (as you've mentioned in question), you might want to consider creating such method returning boolean (note that returning boolean ( true or false ) is not equal to returning 1 or 0 in Java): 如果你想创建一个方法 (正如你刚才提到的那样),你可能要考虑创建这样的方法返回boolean (注意返回booleantruefalse )不等于在Java中返回10 ):

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

If your intention was to return 1 when condition is fulfilled and - for example - 0 , when it's not, you need to change return value of that method to int : 如果你的意图是在条件满足时返回1并且 - 例如 - 0 ,当它不是时,你需要将该方法的返回值更改为int

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

That way you can pass your S string as argument of that method like this: 这样你可以传递你的S字符串作为该方法的参数,如下所示:

checkIfContainsOnlyParenthesis(S);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM