I have a small regex snippet in ruby below which is replacing “: [\w]” with ‘: ~’
>> "name: Name, phone_number: Phone Number, inactive: Inactive ".gsub(/[:]\s[\w]/, ': ~')
=> "name: ~ame, phone_number: ~hone Number, inactive: ~nactive "
How can I modify the gsub expression to add the first character back into the replaced string, i.e:
=> “name: ~Name, phone_number: ~Phone Number, inactive: ~Inactive “
Thanks
First, you don’t need
[]around a single character/special character group, as it makes only sense you want to group multiple characters together. Your regex is equivalent to/:\s\w/.To solve your problem, you can either use a capture group and reinsert the captured letter:
Or use a lookahead to not replace the letter in the first place:
Maybe you’d rather want to use
/:\s+(?=\w)/, which would allow more than one space before the next character.