1

I try to implement a conversion a string: "(foo)" to an Array:[foo] where foo is a nested structure.

For instance, we have a string : "( ('hello' ('world')) (bar) )", and this is supposed to be converted to

[['hello', ['world']], [MasterObj['bar']]]

To get started, let's the problem simplified,

"( (foo) (bar) )" --f--> ["(foo)", "(bar)"]

If I can obtain a function to make this job done, the nested object can be finished recursively.

With a very primitive regex, I could write:

 var src = "( (foo) (bar) );"

 var src1 = src.match(/\(.*\)/g);     

src1 = ['( (foo) (bar) )']

At least, matched parenthesis detected.

 var src = "(foo) (bar)";

 var src1 =src.match(/\(.*\)/g);        

src1 = ['( foo) (bar )'] parenthesis is unmatched.

So, here's my question:

How would you match contents inside of matched parenthesis that is most outside?

Is there a common pattern or regex?

Thanks for your thought.

2 Answers2

2

Having read someone around here wrote stuck, I found a very simple way to match bracket things.

Using regex is rather complicated for this solution.

Say we have a complicated nested list

(a ((b) (c(d)) e))

We have a cursor on the string, and

  • Start from the head - before the first ( with count = 0, then move the cursor to the end.

  • Every time the cursor encounter (, increment the count.

  • Every time the cursor encounter ), decrement the count.

  • When the count === 0 that is the matched ).

In this sample, during the cursor moving from the head to the end, the count goes ->

0 1 2 3 2 3 4 3 2 1 0 < matched!

0

I don't really fully understand what you are trying to accomplish, but I think you are running up against trying to handle nested patterns with regexes. I that case, you can't do it. Regexes just aren't the right tool.

Community
  • 1
  • 1
femtoRgon
  • 31,005
  • 7
  • 54
  • 82
  • Thanks, I've just found an answer by myself. Please refer my Answer here. –  Feb 08 '14 at 01:00