-2

Suppose you have a string like this

.((((((.(((((((((((((((((((((...((((...)))).((((...))))))))))))))))))))))))))))))).

and I want to omit the part ...((((...)))).((((...))) and get only the outer level of parenthesis. How can I do this in Perl?

Usually the strings I encounter in my work are something like this

(((((.(((((((((((((((((((((...((((((.....))))))..........))))))))))))))))))))))))))

and in this case it is easy to implement using index function to specify the position of the last ( and the first ), but in the nested case I tried using stacks to implement but it didn't work.

This is the first nested loop to be omitted .((((((.(((((((((((((((((((((...((((...)))).((((...))))))))))))))))))))))))))))))). and this is the second .((((((.(((((((((((((((((((((...((((...)))).((((...))))))))))))))))))))))))))))))). according to this I must omit all the characters in between these parenthesis .((((((.(((((((((((((((((((((...((((...)))).((((...))))))))))))))))))))))))))))))).

2 Answers2

2

Use substitution i.e. the following s/<regular expression>//

Remember the brackets and full stop needs to be escaped.

EDIT

Here is the regular expression in the substitution

$var =~s%\.\.\.\(\(\(\(\.\.\.\)\)\)\)\.\(\(\(\(\.\.\.\)\)\)%%;
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

You can use the code from this answer by the ingenious SO user ikegami

Parsing string with nested parentheses using Parse::RecDescent

with a slight modification: Change this line

STRING : /\w+/

to this

STRING : /[\w\.]+/

and then call the $parser->parse() method with some of your data.

You can also flatten the $tree using this code:

print(Dumper(flatten($tree)));


sub flatten {
    map { ref eq 'ARRAY' ? flatten(@$_) : $_ } @_
}

But maybe you have code already to process the parse tree generated.

Community
  • 1
  • 1
knb
  • 9,138
  • 4
  • 58
  • 85
  • I did but I got a lot of errors – user1351343 Jul 24 '13 at 13:00
  • so maybe your strings are not properly nested, or you have extra chars in your strings that you need to include in the regex. Can't really help you with messy data, sorry about that. – knb Jul 24 '13 at 14:37