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?
You need to capture \\w
to be able to refer to the submatch.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.