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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With