Replacing partial regular expressions in place with Ruby

I want to convert the following text

This is a ![foto](foto.jpeg), here is another ![foto](foto.png)

at

This is a ![foto](/folder1/foto.jpeg), here is another ![foto](/folder2/foto.png)

In other words, I want to find all the paths to the images enclosed between the brackets (text in Markdown syntax) and replace them with other paths. A string containing the new path is returned as a separate function real_path.

I would like to do this using String#gsubin my block version. Currently my code is as follows:

re = /!\[.*?\]\((.*?)\)/

rel_content = content.gsub(re) do |path|
    real_path(path)
end

The problem with this regex is that it will match ![foto](foto.jpeg), not just foto.jpeg. I also tried another regexen like (?>\!\[.*?\]\()(.*?)(?>\)), but to no avail.

My current workaround is to split the path and compile it later.

Ruby, , ?

. , Ruby regexen lookbehinds. , , , .. /(pre)(matching-part)(post)/, .

re = /(!\[.*?\]\()(.*?)(\))/

rel_content = content.gsub(re) do
    $1 + real_path($2) + $3
end
+5
3

( ):

s = 'This is a ![foto](foto.jpeg)'

s.sub!(/!(\[.*?\])\((.*?)\)/, '\1(/folder1/\2)' )

p s  # This is a [foto](/folder1/foto.jpeg)
+5

- , :

str = "This is a ![foto](foto.jpeg), here is another ![foto](foto.png)"

str.gsub(/\!\[[^\]]*\]\(([^)]*)\)/) do |image|
  image.gsub(/(?<=\()(.*)(?=\))/) do |link|
    "/a/new/path/" + link
  end
end

#=> "This is a ![foto](/a/new/path/foto.jpeg), here is another ![foto](/a/new/path/foto.png)"

, , . image - , ![foto](foto.jpeg), link - , foto.jpeg.

[EDIT] : Ruby lookbehds ( ):

lookbehinds (?<=regex) (?<!regex) , regex - , . Regexp lookbehind - , , . , . ( lookaheads, ).

[foto] (foto ), lookbehind - . , lookbehind - , , , , ( ).

, real_path, .

, ,

+4

$1 ($2 ..).

:

, , $1, $2, $`, $&, $' . , , .

+3
source

All Articles