简体   繁体   中英

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. The pattern you are trying is failing because it only matches a single character - for example, "{".matches("[{(\\\\[\\\\])}]") would return 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):

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 :

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:

checkIfContainsOnlyParenthesis(S);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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