正则表达式,用逗号分隔的逗号分隔 [英] Regular expression to split on commas not enclosed in parenthesis
问题描述
我无法编写正则表达式,以便在String.split(Java)表达式中使用,例如仅在逗号上拆分而不在括号中。
I have not been able to write a regular expression, to use in a String.split (Java) expression such as to only split on comma which are not in parentheses.
示例:
(54654,4565):( 45651,65423) ,4565:45651,(4565,4564):45651
(54654,4565):(45651,65423),4565:45651,(4565,4564):45651
应该产生3个字符串:
- (54654,4565):( 45651,65423)
- 4565:45651
- ( 4565,4564):45651
任何帮助非常感谢。
推荐答案
你可以只用一个前瞻来做到这一点,这比看起来更容易使用。
You can do this with just a lookahead, which is easier to work with than lookbehind.
String[] parts = str.split(",(?![^()]*+\\))");
但其他响应者是对的:如果你不能自己想出这个正则表达式,当需求发生变化时你会怎么做?你可能更了解一个你真正理解的冗长解决方案。
But the other responders are right: if you couldn't come up with this regex on your own, what will you do when the requirements change? You're probably better off with a long-winded solution that you actually understand.
这篇关于正则表达式,用逗号分隔的逗号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!