user1883793 user1883793 - 2 years ago 53
Ruby Question

how to prepend each letter with a symbol using Regex

I have a string time format like this:

d-m-Y H:i
. I want to format it like this:
%d-%m-%Y %H:%i

How do I prepend each letter with
using regular expressions?

Answer Source

This is pretty basic using String#gsub:

str = "d-m-Y H:i"
str.gsub(/[a-z]/i, '%\0')
# => "%d-%m-%Y %H:%i"

In the replacement string '%\0', \0 represents the entire match, which in this case is the matched letter, so this says, "Replace each letter with a % followed by the letter."

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download