示例:
String = "(a(b[}7cv)))"
数组应该如下所示:["(","(","[","}",")",")",")"]
我的尝试:
if(s.charAt(i) == "(" ){
//add to array}
您可以简单地使用regex找到它们,并将它们添加到List 中
public static void main(String[] args) {
String foo = "(a(b[}7cv)))";
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("\W")
.matcher(foo);
while (m.find()) {
allMatches.add(m.group());
}
System.out.println(allMatches);
}
如果它只是你想要的括号,你可能想把"[(){}\]\[]"
作为Pattern.compile
的正则表达式
如何获得非字母数字并添加到列表
String s = "(a(b[}7cv)))";
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);
var list = new ArrayList<String>();
while (m.find()) {
list.add(String.valueOf(s.charAt(m.start())));
}
System.out.println(Arrays.toString(list.toArray()));
输出
[(, (, [, }, ), ), )]