如果不在方括号或括号内,则用逗号分隔字符串

时间:2016-08-03 15:26:00

标签: java regex

我有一个长字符串,只要逗号不在方括号或括号内,我想通过用逗号分隔它来将其设置为数组。我尝试了几种变化,但没有得到我正在寻找的......

示例1:

Harry Potter, Hermione, (Severus, Snape)
Returns:
Harry Potter
Hermione
Severus, Snape

示例2:

Harry Potter, [and, the chamber, of secrets], Hermione, (Olivanders, Wands)
Returns:
Harry Potter
and, the chamber, of secrets
Hermione
Olivanders, Wands

1 个答案:

答案 0 :(得分:6)

您可以将以下正则表达式与全局标记一起使用。

,(?![^\(\[]*[\]\)])

这是demo。 它的灵感来自https://stackoverflow.com/a/9030062/1630604

相关问题