Java字符串拆分多个字符

uni*_*niQ 1 java regex string split

我想分割一个Java字符串:

"[1,2,3,4,5]"
Run Code Online (Sandbox Code Playgroud)

所以我有一个只有整数的数组

1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

没有",[]"

我试过了

String[] test = x.split("(, )|(\\[\\)|(\\]\\)");
Run Code Online (Sandbox Code Playgroud)

我在另一个线程中发现但它无法正常工作.它保留一个空字符串test[0].

Rio*_*ams 5

在这种情况下最简单的方法似乎只是替换方括号字符[和](通过replace()或replaceAll()调用),然后split()使用以下命令执行您的功能:

// Replace the square braces and then split using a comma
String[] output = input.replace("[", "").replace("]", "").split(",");
Run Code Online (Sandbox Code Playgroud)

要么 :

// Replace the square braces and then split using a comma
String[] output = input.replaceAll("\\[|\\]", "").split(",");
Run Code Online (Sandbox Code Playgroud)