简体   繁体   English

在文本中添加 html 超链接标记站点

[英]add html hyperlink tag site in text

I'm new in Python and working on kind of converter from plain text, to "readable" html.我是 Python 新手,正在研究从纯文本到“可读”html 的转换器。 So I've made almost all except making links to cool hyperlinks.所以除了制作超酷超链接的链接之外,我几乎制作了所有内容。

So, I need find and replace in text links, there is an example :所以,我需要在文本链接中查找和替换,有一个例子:

Input:输入:

random_text
another_random_text: https://example.com/random_text
random_text

Output:输出:

random_text
another_random_text: <a href="https://example.com/random_text">example.com</a>
random_text

I'm stucked with it and have no idea how to detect a link and cut it right我被它困住了,不知道如何检测链接并正确剪切

You can use regular expression for the task ( Regex101 link ).您可以对任务使用正则表达式( Regex101 链接)。 For example:例如:

import re

s = '''
random_text
another_random_text: https://example.com/random_text
random_text
'''

s = re.sub(r'(https?://([^/]+)(?:[^\s]*))', r'<a href="\1">\2</a>', s)
print(s)

Prints:印刷:

random_text
another_random_text: <a href="https://example.com/random_text">example.com</a>
random_text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM