1

I'm trying parse input string which looks like array[digit or expression or array, digit or expression or array] So I need to get values in [ , ]. I was trying to get them using this regex:

(array1)\[(.*)\,(.*)\]

to get values of (.*) capturing groups, but it doen't work, because it's greedy quantifier, so in the case of:

array1[ array2[4,3] , array2[1,6] ]

I will get array2[4,3] , array2[1, as first capturing group and 6 as a second which is not right.

How can I get array2[4,3] as first and array2[1,6] as second capturing group? Or array2[array3[1,1],3] and 5+3 if the input string is array1[ array2[array3[1,1],3] , 5+3 ]?

0

1 Answer 1

3

You can make use of balancing groups:

array\d*\[\s*((?:[^\[\]]|(?<o>\[)|(?<-o>\]))+(?(o)(?!))),\s*((?:[^\[\]]|(?<o>\[)|(?<-o>\]))+(?(o)(?!)))\]

ideone demo on your last string.

A breakdown:

array\d*\[\s*    # Match array with its number (if any), first '[' and any spaces
(
  (?:                 
    [^\[\]]      # Match all non-brackets
  |
    (?<o>\[)     # Match '[', and capture into 'o' (stands for open)
  |
    (?<-o>\])    # Match ']', and delete the 'o' capture
  )+
  (?(o)(?!))     # Fails if 'o' doesn't exist
)
,\s*             # Match comma and any spaces
(                # Repeat what was above...
  (?:            
    [^\[\]]      # Match all non-brackets
  |
    (?<o>\[)     # Match '[', and capture into 'o' (stands for open)
  |
    (?<-o>\])    # Match ']', and delete the 'o' capture
  )+
  (?(o)(?!))     # Fails if 'o' doesn't exist
)
\]               # Last closing brace
Sign up to request clarification or add additional context in comments.

4 Comments

This fails if you add a third array.
@rbrundritt There's only one array with (at most) 2 sub arrays (but which can have more sub arrays) in the question. I'm not sure what you mean...?
Wouldn't it make more sense to allow it to work with any number of sub arrays.
@rbrundritt Then the capture groups wouldn't be needed. OP would have to make only one capture group containing all the sub arrays separated by comma in this condition.

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.