Regular expression to check if brackets are nested

I have a large number of files which contain lines with matched braces. I do not care if the brackets are matched or not.

I'd like to check if any braces are nested, by checking which comes first after an opening bracket - a closing or another opening bracket. I assume that all brackets are matched, and that there is at most one outer-bracket per line. (Ie, [foo[bar]] is a valid line, [foo][bar] is not, because the second bracket pair isn't nested).

I can get everything inside a bracket pair from this question using 's/.*\[\([^]]*\)\].*/\1/g', but I'm unsure how to re-test the grabbed string for further matches.

For example, given the following string:

foo [ bar, [baz] ]

the steps I think I would take are:

  1. Traverse from the left-hand side until I see an opening bracket. (If none is found, ignore the line).
  2. Non-greedily search from the opening brace until either [ or ] is encountered. If [, brackets are nested, so return the line. If ],

Ideally I'd like a sed or unix-tool based solution, but others are acceptable (perl, for example). Any help would be appreciated.


perl -ne 'print if /\[[^\]]*\[/' your_file

tested below:

> cat temp
foo [ bar, [baz] ]
foo [ bar, baz ]
foo [ bar ]
foo [ bar, baz] ]
foo  bar, [baz] ]
> perl -ne 'print if /\[.*\[/' temp
foo [ bar, [baz] ]

Use the recursive regexp to check brackets match AND they are nested. Its no point to check nesting without syntax check cus this can break out checking result. For example:

my $regex = qr/\[([^\[\]]+?|(??{$regex}))*\]/;
if( $line =~ /^[^\[\]]*\[$regex\][^\[\]]*$/ ) #Valid

Need Your Help

Android draw path

android performance path draw

It is not good idea to construct path object every time when call Draw method.

received-im-msg signal message

c signals instant-messaging libpurple

I want to make a program that logs in few IDs on different protocols, receives the messages and gives answers to different messages (commands).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.