Ruby gsub regex to add the first matched character back into the replaced string
Вопрос
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:
s.gsub(/:\s(\w)/, ': ~\1')
# => "name: ~Name, phone_number: ~Phone Number, inactive: ~Inactive "
Or use a lookahead to not replace the letter in the first place:
s.gsub(/:\s(?=\w)/, ': ~')
# => "name: ~Name, phone_number: ~Phone Number, inactive: ~Inactive "
Maybe you'd rather want to use /:\s+(?=\w)/
, which would allow more than one space before the next character.
Не связан с StackOverflow