在文本中查找URL并包装在锚标记中

And*_*rew 3 ruby

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

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'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

如果您能指出我可以用作示例的现有Ruby markdown解析器中的代码,则可以获得奖励积分.

Phr*_*ogz 10

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

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

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

See more at http://www.google.com.
Run Code Online (Sandbox Code Playgroud)

... INTO ...

See more at <a href="http://www.google.com.">http://www.google.com.</a>
Run Code Online (Sandbox Code Playgroud)

所以你可能想要使用正则表达式来弄清楚URL应该在哪里结束.