分裂的正则表达式模式 [英] Regex pattern for split

查看:142
本文介绍了分裂的正则表达式模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解决这个问题。


  • 逗号:拆分条款

  • 双引号:字符串值(忽略特殊字符)

  • [] 数组

  • , comma : split terms
  • " double quote : String value (ignore special char)
  • [] array

例如:

输入: a = 1,b =1,2,3,c = [d = 1,e =1,2,3]

预期产出:

    a=1
    b="1,2,3"
    c=[d=1,e="1,2,3"]

但是我无法达到上述结果。

But I could not get above result.

我写了下面的代码:

 String line = "a=1,b=\"1,2,3\",c=[d=1,e=\"1,11\"]";
 String[] tokens = line.split(",(?=(([^\"]*\"){2})*[^\"]*$)");
 for (String t : tokens)
      System.out.println("> " + t);

我的输出是:

a=1
b="1,2,3"
c=[d=1
e="1,11"]

我需要更改什么来获得预期的输出?我应该坚持正则表达式还是其他解决方案可以更灵活,更容易维护?

What do I need to change to get the expected output? Should I stick to a regular expression or might another solution be more flexible and easier to maintain?

推荐答案

这个正则表达式可以解决问题:

This regex does the trick:

",(?=(([^\"]*\"){2})*[^\"]*$)(?=([^\\[]*?\\[[^\\]]*\\][^\\[\\]]*?)*$)"

它的工作原理是为匹配对添加前瞻逗号后的方括号 - 如果你里面一个方括号内的术语,当然你不会有平衡括号。

It works by adding a look-ahead for matching pairs of square brackets after the comma - if you're inside a square-bracketed term, of course you won't have balanced brackets following.

以下是一些测试代码:

String line = "a=1,b=\"1,2,3\",c=[d=1,e=\"1,11\"]";
String[] tokens = line.split(",(?=(([^\"]*\"){2})*[^\"]*$)(?=([^\\[]*?\\[[^\\]]*\\][^\\[\\]]*?)*$)");
for (String t : tokens)
    System.out.println(t);

输出:

a=1
b="1,2,3"
c=[d=1,e="1,11"]

这篇关于分裂的正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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