Domanda

I have a bunch of markdown image paths in several files and I want to change the root directory. The regex for the image tag is this:

/\!\[image\]\((.*?)\)/

I need to be able to grab the group, parse out the filename and give it a new path before returning it to gsub to be substituted out.

For instance, I want to find all strings like this:

![image](/old/path/to/image1.png)

And convert them to:

![image](/new/path/to/image1.png)

I know I can do this in a gsub block, I'm just not very clear how it works.

È stato utile?

Soluzione

Here's one way, verbosely for clarity's sake:

markdown = "![image](/old/path/to/image1.png)"
regex = /(\w+.png)/
match_data = regex.match markdown

p base_name = match_data[1]
#=> "image1.png"

p new_markdown = "![image](/new/path/to/#{base_name})"
#=> "![image](/new/path/to/image1.png)"

More succinctly:

p markdown.gsub( /\/.+(\w+.png)/, "/new/path/to/#{$1}" )
#=> "![image](/new/path/to/image1.png)"

Altri suggerimenti

You can use a regular expression with positive lookbehind and positive lookahead to replace only the filename part in the original String. I have a new_path variable holding the new path, and simply substitute that using .sub.

img = "![image](/old/path/to/image1.png)"
new_path = '/new/path/to/image1.png'
p img.sub(/(?<=!\[image\]\()[^)]+(?=\))/, new_path)
# => "![image](/new/path/to/image1.png)"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top