Jes Jes - 1 year ago 49
Ruby Question

Replacement with regular expression and capture

The method below is supposed to transform


def zebulansNightmare(string)

With string
, I expect
to match
after the
. I understood that
is the first matched letter: the capital letter. But it works like it's substituting
with the capital letter. Why has the

Answer Source

You are right that $1 is the captured value, however, the gsub matches the letter with _ before it, and the whole match gets replaced. You need to reinsert _ to the result:


See the IDEONE demo

BTW, if you only plan to match _ followed with a letter (so as not to waste time and resources on trying to turn non-letters to upper case), you can use the following regex:


Where \p{Ll} is any lowercase Unicode letter.