【问题标题】:java extract elements separated by comma from a String [duplicate]java从字符串中提取用逗号分隔的元素[重复]
【发布时间】:2018-05-28 16:10:49
【问题描述】:

我有一个这样的字符串:

String input= 'hello',2,[5,6],'city'.

所以字符串是由不同种类的元素组成的。

我“只是”需要提取用逗号分隔的元素。但是我找不到 一种避免在元素[5,6] 中考虑逗号的方法。 我尝试使用 split() 方法并考虑许多不同的正则表达式 达到我的目标,但没有成功。

【问题讨论】:

  • 提供的输入无效字符串应包含在文字中(双引号)
  • str.split(",(?![^\\[\\]]*\\])"), demoooo
  • 如果您正在处理 CSV,请获取 CSV 解析器。

标签: java regex string split


【解决方案1】:

,(?![^\[]*[]]) 为这份工作工作。

class Test {
    public static void main(String[] args){

        String test = "'hello',2,[5,6],'city'";
        String[] output = test.split(",(?![^\\[]*[]])");

        for (String s : output)
            System.out.println(s);

    }
}

输出:

'hello'
2
[5,6]
'city'

【讨论】:

  • 非常感谢。我能问你这个正则表达式是如何工作的吗?圆括号内的文字对我来说不是很清楚。
  • @Marco the book 以了解正则表达式及其变体的作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2017-06-06
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多