Ruby - Regex for matching brackets?

Johnson picture Johnson · Sep 22, 2014 · Viewed 7.5k times · Source

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

Answer

sawa picture sawa · Sep 22, 2014
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