gpt4 book ai didi

ruby - 在文本中查找 URL 并包裹在 anchor 标记中

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:34 24 4
gpt4 key购买 nike

我基本上是在编写自己的 Markdown 解析器。我想检测字符串中的 URL,如果它是有效的 URL,则用 anchor 标记将其包装起来。例如:

string = 'here is a link: http://google.com'
# if string matches regex (which it does)
# should return:
'here is a link: <a href="http://google.com">http://google.com</a>'

# but this would remain unchanged:
string 'here is a link: google.com'

我怎样才能做到这一点?

如果您能指出我可以用作示例的现有 Ruby markdown 解析器中的代码,将加分。

最佳答案

通常:使用正则表达式查找 URL 并将它们包装在您的 HTML 中:

urls = %r{(?:https?|ftp|mailto)://\S+}i
html = str.gsub urls, '<a href="\0">\0</a>'

请注意,此特定解决方案将转换此文本:

See more at http://www.google.com.

……进入……

See more at <a href="http://www.google.com.">http://www.google.com.</a>

因此,您可能想尝试一下正则表达式,以确定 URL 真正应该在哪里结束。

关于ruby - 在文本中查找 URL 并包裹在 anchor 标记中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8996447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com