简体   繁体   中英

Ruby `gsub` of escape character

File escape.txt contains "/\\\\/" (slash, backslash, backslash, slash). File test_gsub.rb has:

content = File.open(ARGV[0]).read
content.gsub! content, content
puts content

This code will output "/\\\\/" (slash, backslash, slash), ie, oneback slash is escaped.

I am wondering if there is a way to disable this escape functionality. I want to output (slash, backslash, backslash, slash).

If I delete gsub , it will output (slash, backslash, backslash, slash).

This feature is important because I need to deal with raw text, and gsub will always escape these escape characters.

content.gsub! content, content => content

In the docs for gsub you can find this

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern's capture groups of the form \\d, where d is a group number, or \\k, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as $&, will not refer to the current match.

If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.

Using a hash instead of a string prevents \\ from being treated specially.

Although the docs for gsub! don't mention the hash it seems to work fine (perhaps it's an oversight)

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