1

The string looks like this "[xx],[xx],[xx]" Where xx is a ploygon like this "(1.0,2.3),(2.0,3)...

Basically, we are looking for a way to get the string between each pair of square brackets into an array.

E.g. String source = "[hello],[1,2],[(1,2),(2,4)]"

would result in an object a such that:

a[0] == 'hello'
a[1] == '1,2'
a[2] == '(1,2),(2,4)'

We have tried various strategies, including using groovy regex:

def p = "[12],[34]"
def points = p =~ /(\[([^\[]*)\])*/
println points[0][2] // yields 12

However,this yields the following 2 dim array:

[[12], [12], 12]
[, null, null]
[[34], [34], 34]

so if we took the 3rd item from every even rows we would be ok, but this does look very correct. We are not talking into account the ',' and we are not sure why we are getting "[12]" twice, when it should be zero times?

Any regex experts out there?

3
  • Your regex can match an empty string (thus, you have nulls and 3 matches) and the regex has 2 capturing groups (thus, you have 3 groups all in all - thus, you have 3 elements in each match). You must be looking for \[([^\[]*)], right? Or do you want to just get rid of a capturing group altogether with (?<=\[)[^\[\]]* Commented Oct 27, 2015 at 12:20
  • You can try: (source =~ /(?:\[([^\]]*)\])*/)*.getAt(1).findAll() Commented Oct 27, 2015 at 12:35
  • (source =~ /(?:[([^]]*)])*/)*.getAt(1).findAll() works! Many thanks! Not sure what its doing though, what does the colon do? Commented Oct 27, 2015 at 12:51

1 Answer 1

1

I think that this is what you're looking for:

def p = "[hello],[1,2],[(1,2),(2,4)]"
def points = p.findAll(/\[(.*?)\]/){match, group -> group }
println points[0]
println points[1]
println points[2]

This scripts prints:

hello
1,2
(1,2),(2,4)

The key is the use of the .*? to make the expression non-greedy to found the minimum between chars [] to avoid that the first [ match with the last ] resulting match in hello],[1,2],[(1,2),(2,4) match... then with findAll you returns only the group captured.

Hope it helps,

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.