使用Java中的Regex在方括号内用逗号分隔值
问题描述:
我有这样的字符串:
String text = "[Values, one, two, three]";
我尝试使用Guava的类Splitter:
I tried do it with Guava's class Splitter:
List<String> split = Splitter.on(",").splitToList(text);
但我的结果是:
[Values
one
two
three]
如何使用Regex获取值为1,2和3的List?
How can I get a List with the values one, two and three using Regex?
答
首先剥离使用 replaceAll()
从字符串中 [
和]
。然后使用 \ * *,\s *
进行拆分,这意味着逗号可以在其之前或之后具有可选空格。
First strip out the [
and ]
from the string using replaceAll()
. Then split using \s*,\s*
which means comma can have optional space before or after it.
String []splits = text.replaceAll("^\\s*\\[|\\]\\s*$", "").split("\\s*,\\s*");
现在将 String
数组转换为 List< String>
使用 Arrays.asList()
。
Now convert the String
array into List<String>
using Arrays.asList()
.