使用Java中的Regex在方括号内用逗号分隔值 [英] Getting values separated by comma inside square brackets using Regex in Java

查看:149
本文介绍了使用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().

这篇关于使用Java中的Regex在方括号内用逗号分隔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆