Regexp在java中拆分字符串

时间:2015-08-31 15:39:44

标签: java regex

String s = "{key1:[1239,6783], key2:[323], key3:[{id: 61519, chart: false}], key4:[6,34,56], key5:[325432,545434]}"

需要使用"," 拆分上述字符串。

预期:

s[0] = {key1:[1239,6783]  
s[1] = key2:[323]   
s[2] = key3:[{id: 61519,chart: false}]  
s[3] = key4:[6,34,56]  
s[4] = key5:[325432,545434]}  

实际:

Splits by considering the commas which is present in the value pair too.  
s[0] = {key1:[1239  
s[1] = 6783]  and it's goes on...

是否可以使用regexp和java执行上述任务?如果是,请向我提供解决方案......

5 个答案:

答案 0 :(得分:1)

如果这是一个可以接受的选项,我宁愿用下面的正则表达式迭代匹配:

\w+\s*:\s*\[[^]]+\]

Regular expression visualization

Debuggex

的可视化

在Java中:

String s = "{key1:[1239,6783], key2:[323], key3:[{id: 61519, chart: false}], key4:[6,34,56], key5:[325432,545434]}";
Pattern p = Pattern.compile("\\w+\\s*:\\s*\\[[^]]+\\]");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.println(m.group());
}

打印:

key1:[1239,6783]
key2:[323]
key3:[{id: 61519, chart: false}]
key4:[6,34,56]
key5:[325432,545434]

答案 1 :(得分:0)

根据逗号后面跟key:

进行拆分
string.split(",\\s*(?=\\w+:\\[)")

string.split(",\\s*(?=key\d+:\\[)")

答案 2 :(得分:0)

您可以使用这个基于前瞻性的正则表达式:

String[] toks = s.split(",(?![^\\[\\]]*\\])\\s*");
for (String tok: toks)
    System.out.printf("<%s>%n", tok);

<强>输出:

<{key1:[1239,6783]>
<key2:[323]>
<key3:[{id: 61519, chart: false}]>
<key4:[6,34,56]>
<key5:[325432,545434]}>

RegEx Demo

答案 3 :(得分:0)

使用负向前看下一个括号char为近距离括号:

String[] pairs = s.split(", *(?![^\\[\\]]*\\])");

如果你想更进一步,将关键:值对解析成一个地图(在一行!):

 Map<String, String> map = Arrays.stream(s.replaceAll("^.|.$", "").split(", *(?![^\\[\\]]*\\])"))
    .map(p -> p.split(":")).collect(Collectors.toMap(a -> a[0], a -> a[1]));

你可以继续前进并递归地将值解析为StringString[]Map<String, Object>,但是你会编写自己的json解析器,你最好还是使用它图书馆。

基本解决方案的一些测试代码:

String s = "{key1:[1239,6783], key2:[323], key3:[{id: 61519, chart: false}], key4:[6,34,56], key5:[325432,545434]}";
Arrays.stream(s.split(", *(?![^\\[\\]]*\\])")).forEach(System.out::println);

输出:

{key1:[1239,6783]
key2:[323]
key3:[{id: 61519, chart: false}]
key4:[6,34,56]
key5:[325432,545434]}

to-map解决方案的一些测试代码:

String s = "{key1:[1239,6783], key2:[323], key3:[{id: 61519, chart: false}], key4:[6,34,56], key5:[325432,545434]}";
Map<String, String> map = Arrays.stream(s.replaceAll("^.|.$", "").split(", *(?![^\\[\\]]*\\])"))
.map(p -> p.split(":")).collect(Collectors.toMap(a -> a[0], a -> a[1]));
System.out.println(map);

输出:

{key1=[1239,6783], key2=[323], key5=[325432,545434], key3=[{id, key4=[6,34,56]}

答案 4 :(得分:0)

您可以使用简单的备用正则表达式分割器("], "

String s = ""{key1:[1239,6783], key2:[323], key3:[{id: 61519, chart: false}], key4:[6,34,56], key5:[325432,545434]}"";

String[]tokens = s.split("], ");

System.out.println(Arrays.toString(tokens));

PS:这取消了结束]