Reputation: 57
I am trying to write a python function and convert markdown format link like: [text] (link), into < a href > tags in HTML. For example:
link(line)
link("Here is the link [Social Science Illustrated](https://en.wikipedia.org/wiki/Social_Science_Illustrated) I gave you yesterday.")
"Here is the link <a href="https://en.wikipedia.org/wiki/Social_Science_Illustrated">Social Science Illustrated</a> I gave you yesterday."
And my code for now is:
def link(line):
import re
urls = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)")
line = urls.sub(r'<a href="\1"></a>', line)
return line
Output:
=> 'Here is the link [Social Science Illustrated] ( <a href="https://en.wikipedia.org/wiki/Social_Science_Illustrated"></a> ) I gave you yesterday.'
So I was wondering how to convert [text] part into correct position?
Upvotes: 1
Views: 1871
Reputation: 1544
from re import compile, sub
def html_archor_tag(match_obj):
return '<a href="%(link)s">%(text)s</a>' %{'text': match_obj.group(1), 'link': match_obj.group(2)}
def link(line):
markdown_url_re = re.compile(r'\[([^\]]*)]\(([^\)]*)\)')
result = sub(markdown_url_re, html_archor_tag, line)
return line
For more information on re.sub
Upvotes: 0
Reputation: 43073
If you just need to convert based on the [text](link)
syntax:
def link(line):
import re
urls = re.compile(r'\[([^\]]*)]\(([^\)]*)\)')
line = urls.sub(r'<a href="\2">\1</a>', line)
return line
You don't have to validate the link. Any decent browser will not render it as a link.
Upvotes: 1