Mike Axiak
Mike Axiak

Reputation: 12004

Split a string and keep matched splitter in list in Groovy

Hey, I have a python background and I'm having a couple of issues with the split function in groovy (but I guess java...). Specifically, I want to retain my split character since I do not know at the time of splitting what it is. So for example, suppose I have the following string:

"(if (= 2 (- 3 1)) 4 (- 3 1))"

I want to split it into:

['', '(', 'if ', '(', '= 2 ', '(', '- 3 1', ')', '', ')', ' 4 ', '(', '- 3 1', ')', '', ')', '']

(note: I'm not trying to write a lisp/scheme parser, this is just an easy example of nested parentheses.)

Is there an easy way to do this in Groovy?

Upvotes: 1

Views: 849

Answers (2)

mfloryan
mfloryan

Reputation: 7685

I don't think you really mean splitting the string. From your example it looks more like you are trying to parse it so what you need is a tokenizer. There are plenty solutions available. Information on lexical analysis might be a good point to start.

Upvotes: 0

Michael Easter
Michael Easter

Reputation: 24468

Regarding the fundamental JDK, this question (and answers) implies that it can be done, but not easily (though this is subjective).

That leaves the Groovy JDK. According to the Groovy JDK doc, particularly the additional methods on String, I don't see anything that gives you what you're asking.

Upvotes: 1

Related Questions