I have a String of the format "[(1, 2), (2, 3), (3, 4)]", with an arbitrary number of elements. I’m trying to split it on the commas separating the coordinates, that is, to retrieve (1, 2), (2, 3), and (3, 4).
Can I do it in Java regex? I’m a complete noob but hoping Java regex is powerful enough for it. If it isn’t, could you suggest an alternative?
You can use
String#split()for this.The
(?<=\\))positive lookbehind means that it must be preceded by). The(?=\\()positive lookahead means that it must be suceeded by(. The(,\\s*)means that it must be splitted on the,and any space after that. The\\are here just to escape regex-specific chars.That said, the particular String is recognizeable as outcome of
List#toString(). Are you sure you’re doing things the right way? 😉Update as per the comments, you can indeed also do the other way round and get rid of non-digits:
Here the
\\Dmeans that it must be splitted on any non-digit (the\\dstands for digit). The.after means that it should eliminate any blank matches after the digits. I must however admit that I’m not sure how to eliminate blank matches before the digits. I’m not a trained regex guru yet. Hey, Bart K, can you do it better?After all, it’s ultimately better to use a parser for this. See Huberts answer on this topic.