HBlend
HBlend

Reputation: 555

Ruby: backslash all non-alphanumeric characters in a string

I have a script where I need to take a user's password and then run a command line using it. I need to backslash all (could be more then one) non-alphanumeric characters in the password. I have tried several things at this point including the below but getting no where. This has to be easy, just missing it.

Tried these and several others:

password = password.gsub(/(\W)/, '\\1')

password = password.gsub(/(\W)/, '\\\1')

password = password.gsub(/(\W)/, '\\\\1')

Upvotes: 1

Views: 1203

Answers (3)

mu is too short
mu is too short

Reputation: 434635

While Jens's pile of toothpicks does have a certain perverse beauty to it I think you might be better off with the block version of gsub:

password = password.gsub(/(\W)/) { |c| '\\' + c }

Go with whatever works for you though.

Upvotes: 4

the Tin Man
the Tin Man

Reputation: 160551

Just as a FYI -

Ruby 1.9 has Regex.escape built-into core:

strings = [
  'foo|bar',
  '(foo|bar)',
  '(?:foo|bar)',
  "foo/bar\n",
  "foo\/bar\n",
  "foo\/bar\\n"
]
regex = strings.map { |s| Regexp.escape(s) }
puts regex
puts '-' * 40

And, like @Nakilon said in the comment, there's inspect:

strings.each do |r|
  puts r.inspect
end
# >> foo\|bar
# >> \(foo\|bar\)
# >> \(\?:foo\|bar\)
# >> foo/bar\n
# >> foo/bar\n
# >> foo/bar\\n
# >> ----------------------------------------
# >> "foo|bar"
# >> "(foo|bar)"
# >> "(?:foo|bar)"
# >> "foo/bar\n"
# >> "foo/bar\n"
# >> "foo/bar\\n"

Upvotes: 0

Jens
Jens

Reputation: 25563

When in doubt, add more backslahes? =)

password = password.gsub(/(\W)/, '\\\\\\1')

This seems to work, see http://ideone.com/n3C0b

Don't ask me why!

Upvotes: 4

Related Questions