括号和正则表达式

时间:2013-11-27 18:39:40

标签: ruby regex

我目前正在进行一项练习,其中我需要找到所有发生的(),[],{},无论是分组还是单个,我都无法找出正则表达式。我之间不需要文本。我已经将它们从我的字符串中过滤掉了:

string_updated = string.gsub(/([a-zA-Z]|\d+)|\s+/, "") 

例如。在这个字符串中:

"I can't ( find the } regular ] expression to ) grab these[."

我想要的只是:(, }, ], ), [

3 个答案:

答案 0 :(得分:0)

您应该可以使用([\(\[\{]).*([\)\]\}])

执行此操作

以下是一个工作示例:http://regex101.com/r/qH1uF5

答案 1 :(得分:0)

您应该使用以下正则表达式:

([][)(}{])

说明:

(            # Start capturing group
  [          # Match any of these characters
    ][)(}{   # Desired chars
  ]          # End of char group
)            # End of capturing group

Live demo

答案 2 :(得分:0)

怎么样:

a = "I can't ( find the } regular ] expression to ) grab these[."
brackets = %w|( ) [ ] { }|
puts a.scan(Regexp.union(brackets)).join(', ') #=> (, }, ], ), [