rus64 rus64 - 1 month ago 11
Ruby Question

Ruby Regexp gsub, replace instances of second matching character

I would like to replace the first letter after a hyphen in a string with a capitalised letter.

"this-is-a-string" should become "thisIsAString"

"this-is-a-string".gsub( /[-]\w/, '\1'.upcase )


I was hoping that \1 would reinsert my second character match \w and that I could capitalise it.

How does one use the \0 \1 etc options?

Answer

There are 2 issues here: 1) you need to capture \w to be able to refer to the submatch, and 2) the \1 is not actually parsed as a backreference here, the .upcase is just applied to an octal character represented with \1.

Use

"this-is-a-string".gsub(/-(\w)/) {$~[1].upcase}
# => thisIsAString

See the Ruby demo

Note that $~[1] inside the {$~[1].upcase} block is actually the text captured with (\w), the $~ is a matchdata object instantiated with gsub and [1] is the index of the first group defined with a pair of unescaped parentheses.

See more details about capturing groups in the Use Parentheses for Grouping and Capturing section at regular-expressions.info.