0

Given this line:

Françoise lui apportait un jour <span class="T6">Aladin ou la </span><span class="T6">Lampe Merveilleuse</span>, un autre <span class="T6">Ali-Baba</span>, le <span class="T6">Dormeur éveillé</span> ou <span class="T6">Sinbad le Marin embarquant à Bassora avec toutes ses richesses</span>. J’aurais bien voulu les revoir....

I can use vim to place asterisks around each capture with a command like this:

:.s;<span class="T6">\([^<]*\)</span>;**\1**;g

Here's the result:

Françoise lui apportait un jour **Aladin ou la ****Lampe Merveilleuse**, un autre **Ali-Baba**, le **Dormeur éveillé** ou **Sinbad le Marin embarquant à Bassora avec toutes ses richesses**. J’aurais bien voulu les revoir....

My question is How can I do this with Ruby?

zabouti
  • 639
  • 2
  • 7
  • 14
  • 1
    https://stackoverflow.com/questions/9898461/ruby-replace-string-with-captured-regex-pattern – markalex Mar 26 '23 at 19:39
  • 2
    Does this answer your question? [Ruby replace string with captured regex pattern](https://stackoverflow.com/questions/9898461/ruby-replace-string-with-captured-regex-pattern) – markalex Mar 26 '23 at 19:39
  • Try `str.gsub(/|<\/span>/, '**')`. [Demo](https://regex101.com/r/w7r4mO/1). See [String#gsub](https://ruby-doc.org/core-2.7.3/String.html#method-i-gsub). The demo link uses the PCRE regex engine but it would be the same with Ruby's regex engine. – Cary Swoveland Mar 26 '23 at 20:21
  • Thanks to all for your suggestions. Cary Swoveland's answer will work but it doesn't use captures from the RE. That's what I'm trying to figure out. – zabouti Mar 27 '23 at 01:56
  • This attempt seems to work using captures: irb(main):145:0> "First I say foobar then I say mumble then I stop.".gsub(%r{(.*?)}){|s|'**'+$1.upcase+'**'} => "First I say **FOOBAR** then I say **MUMBLE** then I stop." But I haven't succeeded in applying that to my original example. I'll keep trying. Where can I find documentation on the use of strings captured by a RegExp in Ruby? – zabouti Mar 27 '23 at 01:56
  • @zabouti did you read the answers linked by markalex? – Max Mar 27 '23 at 15:38
  • found: https://www.fullstackruby.dev/string-theory/2020/11/05/gsub-blocks-partitions-string-scanners-oh-my/
    irb> '...Françoise lui apportait un jour Aladin ou la Lampe Merveilleuse, un autre Ali-Baba...'.gsub(%r{(.*?)}){|s| "'"+$1+"'"}.gsub(/''/,"") => "...Françoise lui apportait un jour 'Aladin ou la Lampe Merveilleuse', un autre 'Ali-Baba'..."
    – zabouti Mar 27 '23 at 19:03
  • Max, yes it did, and the tiny example by gaurav.singharoy didn't really explain what I needed, but it did help me search and finally find https://www.fullstackruby.dev/string-theory/2020/11/05/gsub-blocks-partitions-string-scanners-oh-my/ which finally answered my questions. Thanks, ge – zabouti Mar 27 '23 at 19:05

0 Answers0