Marco Song Marco Song - 1 year ago 69
Ruby Question

Check whether a character is ( { [ using regular expressions

I want to check whether a character is one of


I can do it like this

if char == "{" || char == "(" || char == "["

But I want to use regular expressions to achieve this.

How to do that?

Answer Source

It's pretty straight-forward, you just add them to a set:

BRACKETS = /[\{\(\[]/

if (char.match(BRACKETS))
  # ...

Where in a regular expression [...] represents a set of matching single characters.

To test that it's only that type of character:

BRACKETS = /\A[\{\(\[]\z/

Now the simplest refactoring of your code without using a regular expression is this:

case (char)
when '{', '(', '['
  # ...

That may or may not be faster than a regular expression, so if performance is key, you might want to test that approach as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download