简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM