简体   繁体   中英

What is an escape character in Ruby?

I would like to split lines which contains [ (bracket: []). However, when I type this as /[/ it is treated as comment.

您需要像/\\[/一样转义[字符。

I infer that you're using string.split , which can use a regex (the stuff between the / /) to indicate what delimiter character it will split the string into a list with.

Well, regexes use the [ and ] characters in a special way, to denote that such a group will match any of the characters inside.

[abc] => matches a, b, or c

Since you actually need to match the [ symbol literally, you need to escape it with the \\ switch

So, write your split as:

string.split(/\[/)

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