How to convert wiki-link images to normal md-link images using python3?

Viewed 98

I have some markdown files containing images in ![[image_links]] a.k.a wiki-link format. I want to convert them into ![image_name](image_link) a.k.a standard markdown image format. I am using python3 for the conversion.

I've used WikiLinks extension, but it doesn't give any satisfactory result. How can I convert them using python 3.x?

I have used regex to find the string as follows:

import re

txt = "The ![[12345]] ![[12345.jpg]] ![[Pasted image 20210519063449.png]] ha ![[Test.jpeg]] haha quick brown 123.45 fox [[jumps]]"
pattern = re.compile(r'!\[\[\D*\d*\.\D{3,4}]]')
print(pattern.findall(txt))

But how to replace them using regex or any other method?

1 Answers

You can use

r'!\[\[(?:(http[^\]]+)|([^\]]+)(\.\D{3,4}))\]\]'

Details:

  • !\[\[ - a literal ![[ string
  • (?: - Non-capturing group
    • ( - Group 1:
    • http[^\]]+ - literal http follow by any char other than a ] one or more times
    • ) - close 1st capturing group
  • | - or
    • ([^\]]+) - Group 2: any char other than a ] one or more times, follow by
    • (\.\D{3,4}) - Group 3: a literal . follow by 3 or 4 of any char other than a digit
  • ) - close non-capturing group
  • \]\] - a literal ]] string
import re

txt = "The ![[12345]] ![[12345.jpg]] ![[Pasted image 20210519063449.png]] ha ![[Test.jpeg]] haha quick brown 123.45 fox [[jumps]] ![[http://example/images/image1.webp]]"

pattern = re.compile(r'!\[\[(?:(http[^\]]+)|([^\]]+)(\.\D{3,4}))\]\]')
match = pattern.findall(txt)
for m in match:
    if m[0]: # http link
        print(f'![{m[0]}]({m[0]})')
    else:
        print(f'![{m[1]}]({m[1]}{m[2]})')
![12345](12345.jpg)
![Pasted image 20210519063449](Pasted image 20210519063449.png)
![Test](Test.jpeg)
![http://example/images/image1.webp](http://example/images/image1.webp)
Related