2

I'm trying to replace every & in a string with \& using String#gsubin Ruby. What I see is confusing me as I was hoping to get milk \& honey:

irb(main):009:0> puts "milk & honey".sub(/&/,'\ &')
milk \ & honey
=> nil
irb(main):010:0> puts "milk & honey".sub(/&/,'\&')
milk & honey
=> nil
irb(main):011:0> puts "milk & honey".sub(/&/,'\\&')
milk & honey
=> nil
irb(main):012:0> 

This is on Ruby 2.0.0p481 on OS X. (I was using String#sub above but plan to use String#gsub for the general case with more than one & in a string.)

1
  • 1
    Note that sub can accept a string argument for literal replacements. So, you can use .sub('&',…) in place of .sub(/&/,…) if you like.
    – Phrogz
    Jul 5, 2015 at 18:04

2 Answers 2

5

When you pass a string as the replacement value to String#sub (or String#gsub), it is first scanned for backreferences to the original string. Of particular interest here, the sequence \& is replaced by whatever part of the string matched the whole regular expression:

puts "bar".gsub(/./, '\\&\\&')   # => bbaarr

Note that, despite appearances, the Ruby string literal '\\&\\&' represents a string with only four characters, not six:

puts '\\&\\&'  # => \&\&

That's because even single-quoted Ruby strings are subject to backslash-substitution, in order to allow the inclusion of single-quotes inside single-quoted strings. Only ' or another backslash itself trigger substitution; a backslash followed by anything else is taken as simply a literal backslash. That means that you can usually get literal backslashes without doubling them:

    puts '\&\&'  # still => \&\&

But that's a fiddly detail to rely on, as the next character could change the interpretation. The safest practice is doubling all backslashes that you want to appear literally in a string.

Now in this case, we want to somehow get a literal backslash-ampersand back out of sub. Fortunately, just like the Ruby string parser, sub allows us to use doubled backslashes to indicate that a backslash should be taken as literal instead of as the start of a backreference. We just need to double the backslash in the string that sub receives - which means doubling both of the backslashes in the string's literal representation, taking us to a total of four backslashes in that form:

puts "milk & honey".sub(/&/, '\\\\&')

You can get away with only three backslashes here if you like living dangerously. :)

Alternatively, you can avoid all the backslash-counting and use the block form, where the replacement is obtained by calling a block of code instead of parsing a static string. Since the block is free to do any sort of substitution or string munging it wants, its return value is not scanned for backslash substitutions like the string version is:

puts "milk & honey".sub(/&/) { '\\&' }

Or the "risky" version:

puts "milk & honey".sub(/&/) { '\&' }
1

Just triple the \:

puts "milk & honey".sub(/&/,'\\\&')

See the IDEONE demo

In Ruby regex, \& means the entire regex, that is why it should be escaped, and then we need to add the literal \. More patterns available are listed below:

\& (the entire regex)
\+ (the last group)
\` (pre-match string)
\' (post-match string)
\0 (same as \&)
\1 (first captured group)
\2 (second captured group)
\\ (a backslash)

Block representation is easier and more human-readable and maintainable:

puts "milk & honey".sub(/&/) { '\&' }
2
  • 1
    Already wanted to add the option with puts "milk & honey".sub(/&/) { '\&' }, but I see Mark already added it :) Jul 1, 2015 at 17:49
  • Anyway, adding it to the answer. Jul 1, 2015 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.