gpt4 book ai didi

ruby - 在ruby正则表达式中以@符号开头的单词之间插入html标签

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:44 25 4
gpt4 key购买 nike

    link = "http://github.com/"
message = "Hi @freedom and @cake please review my commit."

expected = "Hi <a href='http://github.com/freedom'>@freedom</a> and <a href='http://github.com/cake'>@cake</a> please review my commit."

如何使用 linkmessage 值实现上面的 expected 字符串?

到目前为止,我可以将不带 @ 符号的 username 提取到数组中。

links = []
message.scan(/@\b[^@][a-z]*\b/).each{|x| links << x.sub('@','')}


2.1.5 :010 > links
=> ["freedom", "cake"]

但是我不知道如何将 linklinks 插入到 message 字符串中。

最佳答案

这是您可以使用的示例代码:

puts "Hi @freedom and @cake please review my commit.".gsub(/@([a-z]+)/i, "<a href='http:\/\/github.com\/\\1'>@\\1<\/a>")

输出:

Hi <a href='http://github.com/freedom'>@freedom</a> and <a href='http://github.com/cake'>@cake</a> please review my commit. 

Tested on TutorialsPoint .

您可以将正则表达式微调为 /(?<=^|\s)@([a-z]+)/i只匹配 @something在空格之后或字符串的开头。

关于ruby - 在ruby正则表达式中以@符号开头的单词之间插入html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775649/

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