Marco Song Marco Song - 1 month ago 8
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

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

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

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

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 '{', '(', '['
  # ...
end

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.