gpt4 book ai didi

Ruby - 用于匹配括号的正则表达式?

转载 作者:数据小太阳 更新时间:2023-10-29 06:47:40 24 4
gpt4 key购买 nike

我想弄清楚字符串是否正确地关闭了括号。

为此,我使用了以下三个括号对。

[]
()
{}

只要格式正确,括号也可以嵌套。

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

[()] - Does contain properly closed brackets.

我试过使用正则表达式,经过一番摸索,我明白了。

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

但是,这有一些问题。

只匹配括号不匹配括号

我不明白为什么它与括号不匹配。

在我的示例中,我清楚地在括号前使用了反斜杠。

输入

[] - 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

关于Ruby - 用于匹配括号的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25979364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com