taylorc93
taylorc93

Reputation: 3716

How to match brackets with regex in ruby

I am currently trying to create a regex that will find this pattern /- - [/. However, since the [ is a special character, I am getting this error:

premature end of char-class: /- - [/ (SyntaxError)

I know this is happening because the compiler is expecting the [ in the regex to close, but I need it to match that in my pattern. How can I do this?

Upvotes: 4

Views: 615

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230541

Yes, brackets are part of regex syntax. If you want to match a literal bracket (or any other special symbol, for that matter), escape with a backslash.

'foo[bar]' =~ /\[/ # => 3

Upvotes: 3

Related Questions