我正在尝试编写一种方法来检查给定字符串是否仅 包含这些{([])} 字符。
// 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;
}
但这永远不会返回 true。
最佳答案
String.matches()
根据模式匹配整个 字符串。您正在尝试的模式失败,因为它仅匹配单个字符 - 例如,"{".matches("[{(\\[\\])}]")
将返回 true。您需要在正则表达式中添加一个重复 - *
如果您想匹配空字符串,或者 +
如果字符串必须包含至少一个字符,如下所示:
if(S.matches("[{(\\[\\])}]+")) {
return 1;
}
关于java - 检查 String 是否只包含这些字符 {([])},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49508030/