replace all text urls with html url
我有一个文本文件,其中包含希望用打开到新选项卡的 a 标记替换的 url。我正在将 .txt 文件转换为 .md 文件并需要可点击的链接。
我在下面展示了 (1) 一个 MWE,(2) 期望的输出 (3) 我最初尝试创建一个函数(我假设这将/可能需要 gsub 和 sprintf 函数来实现):
MWE:
1
2 3 4 5 |
x <- c(“content here: http://stackoverflow.com/”,
“still more”, “http://www.talkstats.com/ but also http://www.r-bloggers.com/”, “http://htmlpreview.github.io/?https://github.com/h5bp/html5-boilerplate/blob/master/404.html” ) |
** 期望的输出:**
1
2 3 4 5 |
> x
[1]”content here: http://stackoverflow.com/” [2]”still more” [3]”http://www.talkstats.com/ but also http://www.r-bloggers.com/” [4]”http://htmlpreview.github.io/?https://github.com/h5bp/html5-boilerplate/blob/master/404.html” |
初步尝试解决:
1
2 |
repl <- function(x) sprintf(“%s”, x, x)
gsub(“http.”, repl(), x) |
使用 “http.\\\\s” 作为正则表达式的一个极端情况是,字符串可能不会像 x[3] 那样以空格结尾,或者 url 包含到 http 中,它不想只解析一次(如见于 x[4]).
请注意,R 的正则表达式是特定于 R 的;
其他语言的答案不太可能起作用
这适用于您的示例 x,并使用您的 repl 方法:
1
|
gsub(“(http://[^ ]*)”, repl(‘\\\\1’), x)
|
或者没有你的 repl 方法:
1
|
gsub(“(http://[^ ]*)”, ‘\\\\1’, x)
|
来源:https://www.codenong.com/21006142/