Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Regex for matching brackets?

I am trying to figure out if a string has properly closed brackets.

To do this, I use the following three bracket pairs.

[]
()
{}

The brackets may also be nested as long as they're formatted properly.

)([]{} - Does not have properly closed brackets because )( is reverse order

[()] - Does contain properly closed brackets.

I've tried using regex and after a bit of fumbling around, I got this.

[^\(\[]*(\(.*\))[^\)\]]*

However, there are a few problems with this.

It only matches parentheses but doesn't match brackets

I don't understand why it didn't match the brackets.

In my examples I clearly used a backslash before the brackets.

Input

[] - true
[()] - true (nested brackets but they match properly)
{} - true
}{ - false (brackets are wrong direction)
}[]} - false (brackets are wrong direction)
[[]] - true (nested brackets but they match properly
like image 406
Johnson Avatar asked Sep 22 '14 17:09

Johnson


1 Answers

non_delimiters = /[^(){}\[\]]*/
Paired = /\(#{non_delimiters}\)|\{#{non_delimiters}\}|\[#{non_delimiters}\]/
Delimiter = /[(){}\[\]]/

def balanced? s
  s = s.dup
  s.gsub!(Paired, "".freeze) while s =~ Paired
  s !~ Delimiter
end

balanced?(")([]{}")
# => false
balanced?("[]")
# => true
balanced?("[()]")
# => true
balanced?("{}")
# => true
balanced?("}{")
# => false
balanced?("}[]}")
# => false
balanced?("[[]]")
# => true
like image 197
sawa Avatar answered Nov 08 '22 16:11

sawa